I'm looking to develop for a game that uses Lua as a scripting language.
I have the following statement:
foe:add_component 'render_info':set_scale(0.5)
I understand that :
means that the calling parent object will be passed into called method as the first argument. But in this case, there are no parentheses after render_info
; there's what seems to be a bare string literal with a method being called on it, which really seems to make no sense.
I also understand the concept of metatables and metamethods, which add_component
may be an example of. However, there are no "blank space" operators to override that I have found. I am wondering if there's something major I'm missing about the grammar of Lua.
What does the above code statement mean? What is each part, and what is it doing?
When we call a function with parentheses, the function gets execute and returns the result to the callable. In another case, when we call a function without parentheses, a function reference is sent to the callable rather than executing the function itself.
Attributes (e.g. imag) are like variables inside the object so you don't use parentheses to access them. Methods (e.g. islower()) are like functions inside the object so they do require parentheses to accept zero or more parameters and perform some work.
In JavaScript, the functions wrapped with parenthesis are called “Immediately Invoked Function Expressions" or "Self Executing Functions. The purpose of wrapping is to namespace and control the visibility of member functions. It wraps code inside a function scope and decrease clashing with other libraries.
Attributes will never have parenthesis since they cannot be executed.
If a function has only one argument and this argument is either a literal string or a table constructor, you can omit the parenthesis on function call.
Quote from the lua reference manual:
A call of the form f{fields} is syntactic sugar for f({fields}); that is, the argument list is a single new table. A call of the form f'string' (or f"string" or f[[string]]) is syntactic sugar for f('string'); that is, the argument list is a single literal string.
So this is equivalent to your call:
foe:add_component('render_info'):set_scale(0.5)
If the only argument is a string or a table constructor, there is no need for parenthesis for a function call. It might not be so clearly said in the manual though: http://www.lua.org/manual/5.3/manual.html#3.4.10
Here is a small example code you can try out:
foe = {}
function foe:add_component(str)
print(str)
return foe
end
function foe:set_scale(scale)
print(scale)
return foe
end
foe:add_component 'render_info':set_scale(0.5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With