Methods in Lua
In Lua, we don’t have structs or explicit method definitions like in some other languages. Instead, we use tables and functions to create similar structures. Here’s how the concepts translate:
We define a
rect
table that acts as our “class”.The
new
function is a constructor that creates and returns a newrect
instance.Methods are defined as functions within the
rect
table. The:
syntax in the method definition and call is syntactic sugar that automatically passes the table (object) as the first argument to the function.Lua doesn’t have a built-in concept of pointers. All tables are reference types, so there’s no need to distinguish between value and pointer receivers.
We can call methods using either the colon syntax (
r:area()
) or the dot syntax with explicit self (rect.area(r)
). Both are equivalent.
To run this program, save it as methods.lua
and execute it with the Lua interpreter:
This example demonstrates how Lua can implement object-oriented concepts using its table and function features. While the syntax and exact mechanics differ from some other languages, the fundamental idea of associating data with methods that operate on that data remains the same.