why can't this Lua function using a self ":" be marked "local" without getting "'(' expected near ':'"
coronasdk, lua
Solution
function scene:createScene(event) ... end
Is syntax sugar for:
scene.createScene = function(self, event) ... end
Which is syntax sugar for:
scene["createScene"] = function(self, event) ... end
You want to do:
local scene["createScene"] = function(self, event) ... end
Which makes no sense.
Another way of putting it: `local` is a qualifier for a variable which makes it local rather than global. What variable would you be qualifying with `local function scene:createScene( event )`?
`createScene` is not a variable, it's a key in the table `scene`.
Actually, that's a bit misleading. When you say:
foo = 10
Without qualification, `foo` becomes global, which is to say it's stored in the global state like this:
_G.foo = 10;
Which of course means the same as this:
_G["foo"] = 10;
When you use the keyword `local`, it doesn't get stored in a table, it ends up stored in a VM register, which is both faster and has more tightly constrained scope.
When you write either of these:
function foo.bar() end
function foo:bar() end
You are explicitly storing the function value in a table (`foo`). Those statements are exactly equivalent to these, respectively:
foo["bar"] = function() end
foo["bar"] = function(self) end
I note the listener functions need to be made local
What do you mean by that? In Lua, a function is a function is a function. It's just another value, like a string or number. Whether it's stored in a global, table, local, or not stored at all is irrelevant.
local foo = print
_G["zap"] = foo
doh = zap
t = { zip = doh }
t.zip("Hello, World") -- Hello, World
assert(print == foo
and zap == foo
and zap == doh
and t.zip == doh)
Here we pass the `print` function around. It's all the same function, and as long as we have a reference to it we can call it.
I don't know Corona, but I'm guessing that event handlers are not specified by naming convention of locals. You need to register it as an event handler. For instance, according to this video a Button object has an `onEvent` field which is set to the handler for that button.
Problem
Why can't this Lua function using a self ":" be marked "local" without getting: '(' expected near ':' That is, in the code below things work. But why can't I make the "scene:createScene" function local (as I get the above-mentioned error when trying). I note the listener functions need to be made local else I have struck cross-scene issues at times in storyboard. These can be marked local and work fine. ``` SceneBase = {} function SceneBase:new() local scene = Storyboard.newScene() local function returnButtonTouch_Listener (event) -- code here end function scene:createScene( event ) -- WHY CAN'T THIS BE LOCAL??? -- code here end return scene end return SceneBase ``` That is why can't the function line read: ``` local function scene:createScene( event ) ```