Lua - Fallback Cases of Other Metamethods



Fallback refers to a condition where a corresponding metamethod is not present in the metatable. In such a case, Lua generally fallbacks to the default behavior for the operation or throws error. In this chapter, we'll explore fallback behavior of few important metamethods with examples.

Fallback for _call metamethods

  • When we try to call a table as a function, Lua will throw an error.

  • But if the table is having corresponding _call metamethod implementation in the associated metatables then Lua will execute that method.

Example - Error in case of calling table as function due to Fallback

main.lua

-- table 1
local table1 = {}

-- set a metatable
setmetatable(table1, {})

-- below statement throws error - syntax error near '+'
table1()

Output

When we run the above program, we will get the following output−

lua: main.lua:8: attempt to call a table value (local 'table1')
stack traceback:
    main.lua:8: in main chunk
    [C]: in ?

Example - Handling calling of table Operation

main.lua

-- table 1
local table1 = {}

-- set a metatable
setmetatable(table1, {})

local metaCall = { __call = function(t, ...) print ("Table called with arguments", ...)  end }
setmetatable(table1, metaCall)
-- prints Table called with arguments 1 2 3 hello world
print(table1(1, 2, 3, "hello", "world"))

Output

When we run the above program, we will get the following output−

Table called with arguments	1	2	3	hello	world

Fallback for _tostring metamethods

  • When we try to get a string representation of table using print or tostring, Lua will look for __tostring metamethod.

  • If the table is having corresponding _tostring metamethod implementation in the associated metatables then Lua will execute that method other a default value is printed similar to 0xXXXXXXXX format.

Example - Default value of toString Operation as Fallback

main.lua

-- table 1
local table1 = { a = 5}

-- print a default string representation
print(table1)

local metaToString = { __tostring = function(t) return "a = " .. t.a  end }
setmetatable(table1, metaToString)

-- print a = 5 as string representation
print(table1) 

Output

When we run the above program, we will get the following output−

table: 0x563ada6fdf40
a = 5

Other metamethods

Other metamethods like __metatable if not defined, then getmetatable() returns the real metatable associated. __mode is used for weak table, the fallback is the default behavior of the underlying process.

Advertisements