Module:Abilities/utils: Difference between revisions

Sur (talk | contribs)
m testing a generic table accessor function
Sur (talk | contribs)
m get_value() adjusted to search number keys first as a string key and then as an integer index
Line 98: Line 98:


-- Generic function to traverse the table
-- Generic function to traverse the table
-- A parameter can be passed that is numerical, like 2; and the function will
-- first try to access the key "2", otherwise it will look for the value at index=2 (3rd value)
function p.get_value(frame)
function p.get_value(frame)
local args = frame.args
local args = frame.args
local value = data
local value = item_data


for i = 1, #args do
for i = 1, #args do
local key = args[i]
local key = args[i]
-- Try converting numeric keys
local num_key = tonumber(key)
if num_key and value[num_key] ~= nil then
key = num_key
end


if type(value) == "table" then
-- First try string key
if type(value) == "table" and value[key] ~= nil then
value = value[key]
value = value[key]
-- Then try numeric key if string didn't work
elseif type(value) == "table" then
local num_key = tonumber(key)
if num_key and value[num_key] ~= nil then
value = value[num_key]
else
return ""
end
else
else
return "Error: Attempted to index non-table at key '" .. tostring(key) .. "'"
return ""
end
end
end


if value == nil then
-- Return final value, convert to string if not nil
return "Error: Invalid key path at '" .. tostring(key) .. "'"
if value == nil then
end
return ""
else
return tostring(value)
end
end
return value
end
end


return p
return p