Search code examples
stringluautf-8overloading

How to overload functions string.byte and string.char to support Unicode UTF-8?


I have custom functions utf8Char (decimal) and utf8Byte(char).

How can I overload the functions string.char(...) and string.byte(s, i, j) in Lua?

Here is an example function what I mean:

local originalStringCharFunction = string.char

-- new function:
function string.char(...)
    local args = {...}
    local chars = {}
    for i, codepoint in ipairs(args) do
        chars[i] = utf8Char(codepoint, originalStringCharFunction)
    end
    return table.concat(chars)
end

Solution

  • i hope this is can help you.

    local override = {
        char = function()
            -- whatever you want here
            print("Hello")
        end,
        byte = function()
            -- whatever you want here
            print("World")
        end
    }
    
    local str = {};
    str.__index = string;
    string = setmetatable(override, str);
    
    string.char() -- Hello
    string.byte() -- World
    print(string.lower("HELLO WORLD!")) -- Old string functions still work