In Lua, you can create a table the following way :
local t = { 1, 2, 3, 4, 5 }
However, I want to create an associative table, I have to do it the following way :
local t = {} t['foo'] = 1 t['bar'] = 2
The following gives an error :
local t = { 'foo' = 1, 'bar' = 2 }
Is there a way to do it similarly to my first code snippet ?
In Lua the table is created by {} as table = {}, which create an empty table or with elements to create non-empty table. After creating a table an element can be add as key-value pair as table1[key]= “value”.
One possibility would be to count the number of elements, by using the metatable "newindex" key. When assigning something not nil , increment the counter (the counter could live in the metatable as well) and when assigning nil , decrement the counter. Testing for empty table would be to test the counter with 0.
Constructors are expressions that create and initialize tables. They are a distinctive feature of Lua and one of its most useful and versatile mechanisms. The simplest constructor is the empty constructor, {} , which creates an empty table; we saw it before.
Tables are the only data structure available in Lua that helps us create different types like arrays and dictionaries. Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need.
The correct way to write this is either
local t = { foo = 1, bar = 2}
Or, if the keys in your table are not legal identifiers:
local t = { ["one key"] = 1, ["another key"] = 2}
i belive it works a bit better and understandable if you look at it like this
local tablename = {["key"]="value", ["key1"]="value", ...}
finding a result with : tablename.key=value
Tables as dictionaries
Tables can also be used to store information which is not indexed numerically, or sequentially, as with arrays. These storage types are sometimes called dictionaries, associative arrays, hashes, or mapping types. We'll use the term dictionary where an element pair has a key and a value. The key is used to set and retrieve a value associated with it. Note that just like arrays we can use the table[key] = value format to insert elements into the table. A key need not be a number, it can be a string, or for that matter, nearly any other Lua object (except for nil or 0/0). Let's construct a table with some key-value pairs in it:
> t = { apple="green", orange="orange", banana="yellow" } > for k,v in pairs(t) do print(k,v) end apple green orange orange banana yellow
from : http://lua-users.org/wiki/TablesTutorial
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With