Please let how to do this with out making it a global variable.
@pac - what exactly are you tring to achieve? You can define a local variable within a function so it is defined at the same value each time you call the function, provided that is you do not use other variables within the local variable definition.
I need it to keep the value it had even if it were changed with out it being global.
@pac - Can you give me some idea on what you are doing with this variable and what values it is likely to hold.
@pac I think the variable type you’re looking for is STATIC. Codea/Lua doesn’t have that, so you stuck with either global or local.
you can emulate it this way: instead of making a static local variable + a fonction, make class that contains the variable and the fonction, then instanciate this object, and voilà…
MyFunc = class()
function MyFunc:init(x)
self.localVariable = x or 0
end
function MyFunc:run()
self.localVariable = self.localVariable + 1
end
function setup()
myFunc = MyFunc()
print(myFunc.localVariable)
myFunc:run()
myFunc:run()
print(myFunc.localVariable)
end
Thanks again Dave yours works
here is another version that looks more like a callable function
MyFunc = class()
function MyFunc:init(x)
self.localVariable = x or 0
-- this part is tricky
mt = getmetatable(self) -- the metatable give access to more control on the object
mt.__call = self.run -- this makes the object callable, so it looks like a function (but is not)
end
function MyFunc:run()
self.localVariable = self.localVariable + 1
end
function setup()
myFunc = MyFunc() -- this creates your callable object
print(myFunc.localVariable)
myFunc()
myFunc()
print(myFunc.localVariable)
end
Here’s another way to make a variable local but still retain it’s value from call to call. Touch or move your finger on the screen to increment the value. This uses projectData to retain the value of the local variable save.
function setup()
show=0
saveProjectData("save",0)
fill(255)
end
function draw()
background(0)
text(show,WIDTH/2,HEIGHT/2)
end
function update()
local save=readProjectData("save")
save=save+1
saveProjectData("save",save)
show=save
end
function touched(t)
if t.state==BEGAN or t.state==MOVING then
update()
end
end
If your value is only needed for the inner working of that function, then you can also pass the variable with its updated value back into the same function over and over.
local function showTime(repetitions, cache)
local jump = 3
cache = cache or ElapsedTime
local jumped_to = cache + jump
print(string.format("timestamp jumped from %s to %s", cache, jumped_to))
if repetitions and repetitions > 0 then
showTime(repetitions - 1, cache)
end
end
showTime(10) -- call the function which calls itself another 9x times