5 posts
Posted 21 December 2013 - 09:09 PM
I have seen multiple points where people have used "." in their programs and ":" in their programs, usually the latter for calling functions in tables (like a file handle). Usually, i was able to use either and thought they were identical in the syntax, but I recently came across
this thread and the solution requires ":" otherwise I get a "index expected, got nil" error. So I was wondering what the syntactical difference was, and the advantages to using one over the other. Thanks for the explanation in advance!
8543 posts
Posted 21 December 2013 - 09:34 PM
The colon is syntactic sugar. These are the same:
object:method("argument")
object.method(object, "argument")
995 posts
Location
Canada
Posted 21 December 2013 - 10:22 PM
Yeah. The : passes the table the function belongs to as it's first argument. It can make code look a bit better (among other things)
myTableForAnObject.someFunction(myTableForAnObject, "some parameter")
V.S.
myTableForAnObject:someFunction("some parameter")
5 posts
Posted 22 December 2013 - 12:40 AM
Thank you for the clear explanation! I was always wondering why people did that.
882 posts
Location
Behind you.
Posted 22 December 2013 - 07:44 PM
So this means that string.length("HELLO") and "HELLO":length() are the same, besides the fact I could just use #?
Edited on 22 December 2013 - 06:44 PM
7508 posts
Location
Australia
Posted 22 December 2013 - 08:23 PM
So this means that string.length("HELLO") and "HELLO":length() are the same, besides the fact I could just use #?
yes, except for the one problem with your colon notation, I'd actually be
("HELLO"):length()
882 posts
Location
Behind you.
Posted 23 December 2013 - 01:01 AM
Okay, sorry about that. I was wondering if I had to do that, but internet broke and I couldn't edit the post.