Game Development Reference
In-Depth Information
Lua Tables Are 1-Indexed!
If you
s a typo in the above code
sample. Surely prime[2] should point to 5, right? Not in Lua! Lua is 1-
indexed, meaning that all arrays start at the index of 1, as opposed to C++,
which is 0-indexed. I guarantee that this rather unfortunate decision by the
developers of Lua will cause bugs in your code. This becomes especially messy
when you pass array indexes between C++ and Lua.
'
re paying attention, you might think there
'
'
It
s important to note that in the above example, prime is just a reference to the real
table object. If you assign prime to another variable, Lua does a simple pointer copy,
and both variables will contain references to the same table.
prime = { 2, 3, 5, 7, 11 } -- the original table
prime2 = prime -- this is just a simple pointer copy
print(prime, prime2) -- > this prints out
table: 02D76278 table: 02D76278
prime2[1] = 10
print(prime[1]) -- > prints out
10
Tables don
s just the default. You can
index tables using anything, including numbers, strings, other tables, functions, or
anything else you want.
'
t have to be indexed using a number, that
'
messyTable = {} -- an empty table
-- index by string
messyTable[
string
]=20
messyTable[
another string
]=
data
-- the data doesn
t have to
-- be consistent either
'
-- index by table
anotherTable = {}
messyTable[anotherTable] = 5
-- index by function
Function X() end
messyTable[X] = anotherTable -- this time the data is another table
As you can see, tables have the ability to get very messy. In practice, you probably
wouldn ' t have a table that was so inconsistent with its keys and data. One interesting
property of Lua tables is that they treat integer-indexed items separately from every-
thing else. Under the covers, tables actually have two sections. One section behaves
like a resizable array and the other like a map. As the programmer, you rarely have to
worry about the differences between these. When you create a table like the prime
table above, you are using the array section. When you create one like messyTable ,
Search WWH ::




Custom Search