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
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.
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"
.
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.
lua中的function
是一个关键字,类似于Scheme或Common Lisp(也是Python)中的lambda
,或者在Ocaml中fun
,用于引入具有闭合变量的匿名函数,即闭包
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.