Hal
Hal

Reputation: 219

Lua custom number concatenation

I have been learning about metatables in Lua and I wanted to implement range operators as in Ruby, so I used this model

debug.setmetatable(1, {
    __concat = function(a, b) 
        if a > b then
            error(table.concat({
                "attempt to create a range of values with a",
                "minimum larger than the maximum"
            }, " "))
        elseif a == b then
            return a
        else
            return unpack((function(nStart,nEnd)
                local nTable = {}
                for it = nStart,nEnd do
                    table.insert(nTable, it)
                end
                return nTable
            end)(a, b))
        end
    end
})

print(6 .. 6) 

But it seems that that it continues to use the default behavior. Is there any way to get this to work? I am aware that I could make a function to emulate the behavior and call it with range(n,n2) or similar but that defeats the purpose. Thanks.

Upvotes: 4

Views: 1581

Answers (1)

Ryan Stein
Ryan Stein

Reputation: 8000

Please see section 3.4.5 of the Lua 5.2 manual.

The string concatenation operator in Lua is denoted by two dots ('..'). If both operands are strings or numbers, then they are converted to strings according to the rules mentioned in §3.4.2. Otherwise, the __concat metamethod is called (see §2.4).

If you want to change this behavior, look into lvm.c, specifically the luaV_concat function.

Upvotes: 4

Related Questions