Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What does Data/Table.insert()?

Asked by 9 years ago

I see in a few scripts (And I mean VERY few) What does this mean?, Is it like a table.insert() or a Data command.

Data={}

Data.Test=function()
print('Hello world!')
end

Data.Test()

1 answer

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

In most languages, list like objects are called either lists or arrays (other names include vectors).

Lua's lists differ in that they are actually implimented as a different data structure called a hashtable.


For example, consider this simpler code:

tab = {}
tab[1] = 3
tab[2] = 5
tab[3] = 7
print( tab[2 + 1] ) -- 7

Here, we assign values to particular keys. The key is the value in the square brackets.

While lists use only the numbers 1, 2, 3, ... as keys, you can use any value as a key (except nil):

othertab = {}
tab = {}
tab[othertab] = "Hi"

print( tab[othertab] ) -- "hi"
print( tab[ {} ] ) -- nil
    -- since `{}` and `othertab` refer
    -- to different objects
print( tab[1] ) -- nil
    -- since `1` and `othertab` are
    -- different things

In fact, table.insert(t,v) more or less is sugar for t[#t + 1] = v.


So what about those . dots?

tab.prop is sugar for tab["prop"], that is, using a string literal as the key.

Thus

Data.Test = function()

end

is storing a function value to Data["Test"] (which you can also call Data.Test)


Perhaps this is clearer:

function addNums(a,b)
    return a + b
end



print(addNums(5,9)) -- 14



summer = addNums
print( summer( 5, 9 ) ) -- 14



data = {}

table.insert( data, addNums )
print( data[1] ) -- function 123456789
print( data[1](5, 9) ) -- 14



other = {}

other[1] = addNums
print( other[1](5, 9) ) -- 14



other["cat"] = addNums
print( other["cat"](5, 9) ) -- 14



other.dog = addNums
print( other.dog(5, 9) ) -- 14
Ad

Answer this question