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

[Solved] Problem with a table within table set at runtime

Started by archit, 31 January 2013 - 01:35 PM
archit #1
Posted 31 January 2013 - 02:35 PM
Hello, and first thanks for taking the time in reading this.

I am making an inventory system, using turtles in retrieving resources from chests. I am wanting to use a multi-dimensional table to store resources and their respective x,z,amount values.

here is the relevant code with everything else snipped out for easy reading.


-----------------------------------------
-- global variables
-----------------------------------------
inventory = {}
function add_item()
   print("name of the item:")
   local name = read()
   print("x pos")
   local x = tonumber(io.read(int))
   print("z pos")
   local z = tonumber(io.read(int))
   inventory.name = {xpos = x,zpos = z}
end

Running it I am receiving the error "'<name>' expected" for the inventory.name = {xpos = x, zpos = z} line

I have also tried setting inventory.name to an empty table, then inserting the x and z in separately but that was giving me same error as well.
theoriginalbit #2
Posted 31 January 2013 - 02:43 PM
I have found that using the . syntax only works when accessing a variable. the Lua documentation seems to back this too, have a read under "dictionaries as tables" http://lua-users.org.&#46;&#46;/TablesTutorial

Fix:

inventory["name"] = {xpos = x, zpos = z}
archit #3
Posted 31 January 2013 - 03:02 PM
Thanks for the response. I was actually using a variable for the . syntax as name was referencing whatever string they were looking for in the program. Your link was very nice, and it seems to insinuate that the . syntax will force whatever follows it into a string therefore never allowing a variable to be used.

changing it to:

inventory[name] = {xpos = x, zpos = z}
Works like a charm. then able to access them by:

inventory[name].xpos
theoriginalbit #4
Posted 31 January 2013 - 03:04 PM
yeh ok sorry, if i had of read the code properly and realised it was a variable i would have told you that way. I have a bad habit of skimming and missing important stuff sometimes.