Hello guys, I am not sure if I am losing my mind but I just want to clarify something about tables. Code below:
function setup()
local table1 = {5,3,1,2,4}
local table2 = {}
table2 = table1
table.sort(table1)
print(table1[1]) --gives 1
print(table2[1]) --gives 1 but shouldn't this be 5???
@archistudent that will work if your table is only one level deep (i.e. no tables within tables). If you have nested tables, then it may be worthwhile creating a deep copy function. http://lua-users.org/wiki/CopyTable
@dave1707@ignatz I will test those out. I think I meant looking for all [“keys”] for an unknown table. For example if there was a table that could be found from an http request, but I don’t know its contents, it seems ignatz’ code can list the keys?
yes. If the table doesn’t have keys, it will just give a list of numbers 1, 2, 3, 4… (because Lua has to have keys, so it just creates them in number order)
@archistudent Here’s a function to get the keys. Call the function passing the table and it will return the keys. As @Ignatz said above, any table value without a key will be given a number for the key.
function setup()
someTable={222,d="qwerty","zxcvb",s=444,555,a="asdfg"}
keys=getKeys(someTable)
print(table.concat(keys," "))
end
function getKeys(t)
local temp={}
for keys in pairs(t) do
table.insert(temp,keys)
end
return temp
end
@archistudent - while you are playing with tables, note you can store functions in them too. This is very useful for creating a library of utility functions. By putting them in a table, you ensure the function and variable names won’t clash with the rest of your code.
@archistudent - they are the same, but the primary use of quotation marks is where you want to define a key that can’t be used as a variable name, eg 1abc. That’s where you need to put it in quotes and inside square brackets.
@archistudent You’ll find that there are different ways of doing the same thing. Some ways use less keying and some ways execute faster. Pick the one that feels right for you.