github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/runtime/lua/runtime.lua (about)

     1  local debug = require"debug"
     2  
     3  local function metastring(instance, val)
     4      debug.setmetatable(instance, {__tostring=function() return val end})
     5      print(instance)
     6      debug.setmetatable(instance, nil)
     7  end
     8  
     9  metastring(nil, "NIL")
    10  --> =NIL
    11  
    12  metastring("hello", "bonjour")
    13  --> =bonjour
    14  
    15  metastring(1, "one")
    16  --> =one
    17  
    18  metastring(1e3, "mille")
    19  --> =mille
    20  
    21  metastring(true, "false")
    22  --> =false
    23  
    24  metastring({}, "{}")
    25  --> ={}
    26  
    27  print(getmetatable({}))
    28  --> =nil
    29  
    30  local t = {}
    31  setmetatable(t, {x=24})
    32  print(getmetatable(t).x)
    33  --> =24
    34  
    35  setmetatable(t, {__metatable={x=42}})
    36  print(getmetatable(t).x)
    37  --> =42
    38