This is a Lua-specific construct. The syntax `table.function` and `table:function`...
September 12, 2025 at 07:52 PM
This is a Lua-specific construct. The syntax table.function
and table:function
indicates two different ways to call a function in Lua, and they behave differently in terms of how they pass the arguments. Here's the breakdown:
Basics
-
table.function
- This syntax refers to directly accessing (and possibly calling) a function from the
table
. - When you call the function like this —
table.function(...)
— you need to explicitly pass the table (or any other required arguments) as an argument, i.e., the function does not automatically take the table as itsself
. - It is equivalent to
table["function"]
.
- This syntax refers to directly accessing (and possibly calling) a function from the
-
table:function
- This syntax is a method-call shorthand in Lua.
- It is equivalent to calling
table.function
but with an implicit "self" parameter. Essentially, it translates totable.function(table, ...)
. - When you define a function as
table:function
, internally it receivesself
as the first parameter.
Example
-- Define a table
table = {}
-- Define a function directly
function table.sayHello()
print("Hello!")
end
-- Define a method with "self" (colon syntax)
function table:speak(message)
print(self) -- self represents the table here
print(message)
end
-- Calling with dot-notation
table.sayHello() -- OUTPUT: Hello!
-- Colon-notation implicitly passes `self`
table:speak("Hi!") -- OUTPUT: table (printed by 'self')
-- Hi!
-- Dot-notation requires passing `self` manually for methods
table.speak(table, "Hi!") -- OUTPUT: table
-- Hi!
When Does It Matter?
-
Use
table.function
when:- The function does not need access to the table it is defined in.
- You are manually passing the
self
parameter or other arguments.
-
Use
table:function
when:- The function is a method intended to operate on the table, and you want
self
to be automatically passed as the first parameter.
- The function is a method intended to operate on the table, and you want
Key Difference:
table.function
is a standard function call.table:function
adds theself
argument to the function call automatically.
This difference becomes very important when designing object-oriented behavior in Lua or when functions depend on their parent table.
Generate your own explanations
Download our vscode extension
Read other generated explanations
Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node