Hi guys, just started learning Lua (thanks to Corona!) this weekend and I am getting pretty close to grokking it.
I have one question which is probably best asked in code.
See “QUESTION” below:
local MakeShaun = function(passedIn)
local \_privateVar = -99
local \_iAmPrivateToo = {}
\_iAmPrivateToo.p1 = "p1"
\_iAmPrivateToo["p2"] = "p2"
\_iAmPrivateToo[1] = "one"
\_iAmPrivateToo[2] = "two"
\_iAmPrivateToo.tbl = {x = 1, y = 2}
-- private can access stuff in this closure
local privateFunction = function()
return "privateFunction::\_privateVar = "..\_privateVar.." and passedIn = "..passedIn
end
-- public interface
return {
-- I can't figure out how to access this from a
-- function inside the same table
publicVar = 2,
publicFunction = function()
print("\_privateVar = "..\_privateVar) --\> -99
print("passedIn = "..passedIn) --\> "hello"
print("\_iAmPrivateToo[2] = ".. \_iAmPrivateToo[2]) --\> "two"
print("\_iAmPrivateToo.tbl.y = ".. \_iAmPrivateToo.tbl.y) --\> 2
print(privateFunction()) --\> "privateFunction::\_privateVar = -99 and passedIn = hello"
-- QUESTION: How can I access "publicVar" from a function in this table?
print("publicVar = "..tostring(publicVar)) --\> Always prints "nil" why?
end
}
end
local myShaun = MakeShaun("hello");
myShaun:publicFunction()
print("myShaun.publicVar = "..myShaun.publicVar) --\> 2
myShaun.publicVar = "Carlos"
print("myShaun.publicVar = "..myShaun.publicVar) --\> Carlos
[import]uid: 11196 topic_id: 5474 reply_id: 305474[/import]