Posted 18 October 2012 - 04:56 AM
Hi,
I'm trying to implement a save function in a class, however I cannot for the life of me figure out how to access the content of the variables.
Suppose the following code in a file "testAPI"
and have a program that makes use of this API:
if I used the line
I can access the variable just fine, however I'd have to use one line per variable. And this I consider inelegant. Aside from the fact that a loop allows for the easy inclusion of additional error checking that would seriously blow up the code if copied over and over.
So the question is: how can I access the variables defined in the new() function within an enclosed function?
I'm trying to implement a save function in a class, however I cannot for the life of me figure out how to access the content of the variables.
Suppose the following code in a file "testAPI"
-- test API - test saving params
function new()
local self = {}
local vara = "string"
local varb = 1
local varc = true
local othervar = "string"
local statusVars = {"vara", "varb", "varc"}
function self:saveStatus()
for _, v in pairs(statusVars) do
-- not working!
print("saving: " .. v .. " - " .. tostring(self[v]))
end
return true
end
function self:someFunc()
-- meaningful code here
self:saveStatus()
end
return self
end
and have a program that makes use of this API:
os.loadAPI("testAPI")
t = testAPI.new()
t:someFunc()
if I used the line
print("saving: vara - " .. vara)
I can access the variable just fine, however I'd have to use one line per variable. And this I consider inelegant. Aside from the fact that a loop allows for the easy inclusion of additional error checking that would seriously blow up the code if copied over and over.
So the question is: how can I access the variables defined in the new() function within an enclosed function?