It's unclear what self
should be. The error says it's a global, which is consistent with the code you have shown.
But, self
is almost exclusively used as a formal parameter to a function and an implicit one at that.
When self
is implicit, the function is called a method because the intent is for it to access fields in a table passed into self
. The method value is almost always held by a field in the same table (or at least, available as such via metamethods).
The colon syntax in a function definition creates a method.
If cooked
was a method then it would make sense for it to access self
. But cooked
is a global.
You might have meant:
function sometable:cooked()
-- ...
-- self is an implicit formal parameter
-- ...
end
How to read the Lua statement above:
- access sometable as a table
- assign its "cooked" field the function value created by the function definition.
(The function definition is compiled from the method syntax, so in the body, self
is the first formal parameter, which is implicit.)
The method could be called like:
sometable:cooked() -- passes sometable as self
The colon syntax in a field function call is a method call.
How to read the Lua statement above:
- access sometable as a table,
- index its "cooked" field,
- call its value as a function, passing sometable as the first parameter,
- discard the result list.
Oddities:
- The syntax for methods is just "syntactic sugar." Methods values are no different than other function values:
- A function created from a function definition using the any syntax can be called using any function call syntax.
- A method need not be called using the method call syntax.
- A non-method can be called using the method call syntax.
self
is not reserved so it can be used as any identifier is.