This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
BatStick's profile picture

Unable to index an array?

Started by BatStick, 21 November 2017 - 06:14 AM
BatStick #1
Posted 21 November 2017 - 07:14 AM
So i have this code:

local Table = {}
table.insert(Table,1)
table.insert(Table,2)
table.insert(Table,3)

function tick()
local index = Table[0]
print(index)
end

tick()

This code outputs nothing. I specifically need to get whatever the last item put in the array is. I'm essentially trying to create a First in Last Out stack but I'm stuck here. Thanks.

-BatStick
Bomb Bloke #2
Posted 21 November 2017 - 09:16 AM
Lua is 1-indexed. Because tables are much more dynamic than arrays, you can put data into slot 0 if you really want to, but table.insert() won't do that for you.

If you wanted to print the last item inserted into the array, then you could use print(Table[#Table]) instead (#Table gives the highest index in the table before a nil value is encountered). If you wanted to knock that value out of the table at the same time (so that repeat calls work their way down your "stack"), you could instead use print(table.remove(Table)).