lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi,

Suppose that there is a userdata value which has a metatable
registered as 'LLVMcontext'. Now look at this:

function x(context: LLVMcontext)
  print(context)
end

ctx = llvm.context() -- Get LLVM context

x(ctx) -- Okay

x({}) -- Fails as follows:

> x({})
stdin:1: type mismatch: expected LLVMcontext
stack traceback:
        stdin:1: in function 'x'
        (...tail calls...)
        [C]: in ?

We can also emulate this in Lua:

mt = { __name = 'MyType' }
-- register metatable
debug.getregistry().MyType = mt

a = {} -- some table
setmetatable(a, mt)

Now we can write:

function x(a: MyType) print(a) end

-- Call x with a
x(a) -- Okay

-- Call x with random table
x({1,2}) -- Fails as follows:

stdin:1: type mismatch: expected MyType
stack traceback:
        stdin:1: in function 'x'
        (...tail calls...)
        [C]: in ?

So what does the bytecode for x look like?

> ravi.dumplua(x)

function <stdin:1,1> (5 instructions at 0000026221BBAE80)
1 param, 3 slots, 1 upvalue, 1 local, 2 constants, 0 functions
        1       [1]     TOTYPE          0 -1
        2       [1]     GETTABUP_SK     1 0 -2  ; _ENV "print"
        3       [1]     MOVE            2 0
        4       [1]     CALL            1 2 1
        5       [1]     RETURN          0 1
constants (2) for 0000026221BBAE80:
        1       "MyType"
        2       "print"
locals (1) for 0000026221BBAE80:
        0       a       1       6
upvalues (1) for 0000026221BBAE80:
        0       _ENV    0       0

The new TOTYPE instruction performs a check on value in register A. Bx
must be a string that will be used to lookup the metatable in the
registry.


The main restriction is that the typename must be a valid Lua name.

Previous post where I mentioned this idea:

http://lua-users.org/lists/lua-l/2017-01/msg00164.html

Feedback welcome!

Regards
Dibyendu