Semicolons (;
) go back a long way in terms of programming. I won't go into too much detail, as a simple Google search will get you much further. But semicolons are required in many programming languages.
Lua's syntax is so flexible that it allows for the use of semicolons if you so please. For example:
...and...
...are equally valid and will compile just fine. This is great for programmers who're used to using semicolons in their code (like if they previously coded in Java or C++).
However, do not mix up semicolons (;
) and colons (:
). In order to understand colons in Lua syntax, you have to understand how functions work from within tables. Let's say we have a table, bar
, and inside bar
we have a function called foo
. foo
also takes two parameters: x
and y
. It looks a little something like this:
Pretty standard. We can invoke this function like any other by indexing bar
:
However, what if we used :
instead?
What happened there? It printed a random memory location, 10, and forgetting about the 20. If you look a little closer, you'll find something interetsing about this:
As you can see, bar
and the table returned by bar:foo()
share the same memory location; they're the same table! This is, in fact, exactly how :
works in Lua. When you call a method in Lua, the first argument in the function will be the table holding the function (in this case, bar
). You may ask, "How's this useful?" Well, consider the following:
In this example, the keyword self
is the table bar
. As earlier defined, bar.x
is equal to 10. When we say self.x
from within the function, we're referring to the value x
in self
, or bar.x
. We're then adding the value y
to self.x
, which simplifies as 10+20
.
I hope this clears up some confusion.
Locked by User#24403
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?