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

Table Inserting

Started by PrinzJuliano, 04 November 2013 - 01:05 PM
PrinzJuliano #1
Posted 04 November 2013 - 02:05 PM
Hello my dear friends,

I got a question on Tables:

I got a table like this


local accounts = {
[1] = {
["some"] = "thing"
},
[2] = {
["some"] = "thing"
},
[3] = {
["some"] = "thing"
},
}

so my question is: if i delete the 2nd entry in this table and this is a table where i add stuff dynamicly,
how can i detect that the 2nd index is free(any free space) to insert new data there instead of at the end of the table?

Thanks for your conclusions.

Your PrinzJuliano
LBPHacker #2
Posted 04 November 2013 - 02:16 PM
If it's not a problem that the entries don't retain the same key, use table.remove and table.insert:
local accounts = {
    [1] = {
        ["some"] = "1st"
    },
    [2] = {
        ["some"] = "2nd"
    },
    [3] = {
        ["some"] = "3rd"
    },
}
table.remove(accounts, 2) -- removes the 2nd entry and decrements the key of the entries with keys larger than 2

--[[
accounts[1] remains the same
accounts[2] ceased to exist
accounts[3] moves to accounts[2]
--]]

print(accounts[2].some) -- prints "3rd"
The best part of that is no matter what happens, you'll be able to iterate through the table with a simple for loop:
for ixEntry = 1, #accounts do print(accounts[ixEntry].some) end

table.insert inserts an entry at the end of the table:
table.insert(accounts, {
    ["some"] = "2nd"
}

print(accounts[3].some) -- prints "2nd"
Bomb Bloke #3
Posted 04 November 2013 - 04:28 PM
If you DO want to have your other values stick to their previous indexes:

-- This builds the same thing as the original table,
-- but Lua infers the line numbers for you:
local accounts = { {["some"] = "thing"}, {["some"] = "thing"}, {["some"] = "thing"} }

accounts[2] = nil  -- This removes the 2nd entry and leaves the others alone.

--[[
accounts[1] remains the same
accounts[2] ceased to exist
accounts[3] remains the same
--]]

-- "#accounts" only returns the highest index of this table before hitting a nil value.
-- "table.getn(accounts)" always returns the highest index of this table.

-- Iterating through the table (prints "thing" then "thing"):
for i=1,table.getn(accounts) do if accounts[i] then
  print(accounts[i].some)
end end

-- Inserting into the table:
accounts[#accounts+1] = {["some"] = "cabbage"}

print("")

-- Iterating through the table (this time prints "thing" then "cabbage" then "thing"):
for i=1,table.getn(accounts) do if accounts[i] then
  print(accounts[i].some)
end end