In Warcraft Vanilla 1.12 Lua there's no built-in support for ("foo %s"):format("xyz") (there's only format("foo %s", "xyz")).

So I thought to add a polyfill of sorts like so:


local _format = assert(format or string.format) -- vanilla-wow-lua does have format on the global scope so we can use it here
local _getmetatable = assert(getmetatable)
local _setmetatable = assert(setmetatable)

local _stringMetatable = _getmetatable(string)
if not _stringMetatable then
    _stringMetatable = { __index = {} } -- standard-lua returns a metatable but wow-lua returns nil
    _setmetatable(string, _stringMetatable)
end

function _stringMetatable:format2(formatString, ...)
    if not unpack then
        return _format(self, formatString, ...) -- official lua
    end

    return _format(self, formatString, unpack(arg)) -- warcraft
end

_stringMetatable.__index.format2 = _stringMetatable.format2

This gets loaded just fine both in official lua (https://www.lua.org/cgi-bin/demo) and on the World of Warcraft 1.12. However if we try to use it like so:

local foobar = ("foo %s"):format2("abc")
print(foobar)

This only works on the official lua. Warcraft throws an error which says "attempt to index a string value".

If I switch over to function-call style then it works on both standard-lua and wow-lua:

local foobar = string.format2("foo %s", "abc")
print(foobar)

I can't understand why Warcraft fails to cooperate in this regard when it comes to strings. Any ideas on how to fix this?

0

There are 0 best solutions below