请帮忙解析以下Lua代码的输出结果成因
Let's break down exactly what's happening here—it all comes down to Lua's key difference between colon (:) and dot (.) syntax when defining and calling functions.
First, let's restate your code for clarity:
local tab ={}; function tab:myFun(var,va1) print(self) -- output 3 print(var,va1) -- output 4, nil end tab.myFun(3,4)
1. The Colon Syntax in Function Definitions is Sugar for self
When you define a function with function tab:myFun(var, va1), this is Lua's syntax shorthand for:
function tab.myFun(self, var, va1)
The colon automatically adds a self parameter as the first argument to the function. By convention, self is meant to refer to the table the function is attached to (in this case, tab).
2. Dot Syntax Calls Don't Pass Implicit self
When you call the function with tab.myFun(3,4), you're using dot syntax—which does not automatically pass the parent table as the self argument. Instead, your arguments are mapped directly to the function's parameters in order:
- The first argument
3gets assigned to the function's first parameter (self) - The second argument
4gets assigned to the function's second parameter (var) - No third argument is provided, so
va1defaults to Lua'snil
This is exactly why your output matches what you saw:
print(self)outputs3(sinceselfis now the value you passed as the first argument)print(var, va1)outputs4andnil(sincevaris the second argument, andva1has no value provided)
What If You Used Colon Syntax for the Call?
If you wanted self to refer to the tab table (the more common use case), you'd call the function with colon syntax:
tab:myFun(3,4)
Here, Lua automatically passes tab as the self parameter, then maps 3 to var and 4 to va1. Your output would change to:
print(self)outputs thetabtable (something liketable: 0xabc123)print(var, va1)outputs3and4
内容的提问来源于stack exchange,提问作者Harish Algat

