Search code examples
luaparentheses

Lua: Workaround for boolean conversion of a class variable when enclosed in parentheses


In the below code, can anyone explain why does t1:print() works but (t1):print fails. I am attempting to make something like (t1 * 3):print() work without using an intermediate variable.

function classTestTable(members)
  members = members or {}
  local mt = {
    __metatable = members;
    __index     = members;
  }

  function mt.print(self)
    print("something")
  end
  return mt
end

TestTable = {}
TestTable_mt = ClassTestTable(TestTable)

function TestTable:new()
   return setmetatable({targ1 = 1}, TestTable_mt )
end

TestTable t1 = TestTable:new()

t1:print() -- works fine. 
(t1):print()  -- fails with error "attempt to call a boolean value"

Solution

  • Lua expressions can extend over multiple lines.

    print
    
    
    
    
    (3)
    

    Will print 3

    So

    t1:print()
    (t1):print()
    

    actually is equivalent to

    t1:print()(t1):print()
    

    or

    local a = t1:print()
    local b = a(t1)
    b:print()
    

    So you're calling the return value of t1:print()

    To avoid that follow Egors advice and separate both statements with a semicolon.

    t1:print();(t1):print()