Ank
Ank

Reputation: 6270

Functions in Lua

I am starting to learn Lua from Programming in Lua (2nd edition) I didn't understand the following in the book.

network = {
          {name ="grauna", IP="210.26.30.34"},
          {name ="araial", IP="210.26.30.23"},
}

If we want to sort the table by field name, the author mentions

table.sort(network, function (a,b) return (a.name > b.name) end }

Whats happening here? What does function (a,b) stand for? Is function a key word or something.

If was playing around with it and created a table order

 order={x=1,x=22,x=10} // not sure this is legal

and then did

 print (table.sort(order,function(a,b) return (a.x > b.x) end))

I did not get any output. Where am I going wrong?

Thanks

Upvotes: 3

Views: 1295

Answers (4)

rid
rid

Reputation: 63600

It's an anonymous function that takes two arguments and returns true if the first argument is less than the second argument. table.sort() runs this function for each of the elements that need sorting and compares each element with the previous element.

Upvotes: 8

Jasmijn
Jasmijn

Reputation: 10477

To answer the second part of your question: Lua is very small, and doesn't provide a way to print a table directly. If you use a table as a list or array, you can do this:

print(unpack(some_table))

unpack({1, 2, 3}) returns 1, 2, 3. A very useful function.

Upvotes: 3

I think (but I am not sure) that order={x=1,x=22,x=10} has the same meaning in Lua as order={x=10}, a table with one key "x" associated with the value 10. Maybe you meant {{x=1},{x=22},{x=10}} to make an "array" of 3 components, each having the key "x".

Upvotes: 4

function in lua is a keyword, similar to lambda in Scheme or Common Lisp (& also Python), or fun in Ocaml, to introduce anonymous functions with closed variables, i.e. closures

Upvotes: 2

Related Questions