Well actually, printing level/wool could be done simply with:
{"Level", "Wool"} -- (instead of setting them as keys)
Since you want to access them like an array, that’s the solution (if no gaps).
You 100% have to use metatables for table->string though (if you make no edits to the structure).
If you are using this as a more of way to share object information within your game I would not return the table as it would then allow other scripts to change the table accidentally.
Instead I would include accessor methods for obtaining data in this list.
local toys = {}
-- jus an example of how you can populate a table with less time messing around with formatting it
local function newDataItem(name, level, itmType, itmTypeVal)
if toys [name] then error("Duplicate name found") end
toys[name] = {Level = level, [itmType] = itmTypeVal}
end
newDataItem("Teddy Bear", 1, "Wool", 2) -- ect
local f = {}
function f:HasToy(name)
return toys[name] ~= nil
end
function f:GetToyInfo(name)
if f:HasToy(name) then
return toys[name] -- a clone should be made of this table
end
end
return f -- return function table
script
local module = require([module path])
print(module:HasToy("Car"))
print(module:HasToy("Teddy Bear"))
local toyData = module:GetToyInfo("Teddy Bear")
print(toyData.Level, toyData.Wool)
In the ‘Teddy Bear’ table, there is no value assigned to the key 1. When you use [], you are assigning the key, so if you wanted to get the value related to level, you do table.Level (or table['Level]', they do the same thing).
In this situation I think you just the ordered of the values back to front – if anything, you should be doing [1] = 'Level'. If you want to be able to find them by that index number, you’ll need to make the Teddy Bear table an array, like this: {"Level", "Wool"}
This is easy to write and works well.