__tostring element in Lua Programming


The _tostring element in Lua receives an argument of any type and converts it to a string in a reasonable format.

If the metatable of e has a "__tostring" field, then tostring calls the corresponding value with e as argument, and uses the result of the call as its result.

The __tostring element method is a part of the metatables that Lua library provides us and is used to modify the behaviour of the table that we get as an output.

The __tostring element method is used to modify the behavior of the output table.

Example

 Live Demo

currtable = setmetatable({ 10, 20, 30 }, {
   __tostring = function(currtable)
      sum = 0
      for k, v in pairs(currtable) do
         sum = sum + v
      end
      return "The sum is: " .. sum
   end
})
print(currtable)
print(type(currtable))

Output

The sum is: 60
table

Updated on: 20-Jul-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements