Skip to content

Instantly share code, notes, and snippets.

@x4fx77x4f
Created October 2, 2020 19:28
Show Gist options
  • Save x4fx77x4f/4794821ad61b644204b0d562e95c36fc to your computer and use it in GitHub Desktop.
Save x4fx77x4f/4794821ad61b644204b0d562e95c36fc to your computer and use it in GitHub Desktop.
Script for checking if string methods behave the same as regular Lua
--@shared
local setfenv = setfenv or debug.setfenv
assert(setfenv, "incompatible version of lua")
local prefix = BRANCH and (SERVER and "GLUA SERVER" or CLIENT and "GLUA CLIENT") or (SERVER and "SF SERVER" or CLIENT and "SF CLIENT") or "LUA"
prefix = prefix..": "
local i = 0
local j = 0
local k = 7
local function test(cond, msg)
j = j+1
if cond then
i = i+1
else
print(prefix.."Failed test "..j..": "..msg)
end
end
local function callback(err, stacktrace)
-- I really, really, really don't like Starfall's custom 'error' objects.
err = type(err) == "table" and err.message or err
err = err:gsub("^.-: ", "")
print(prefix.."Error: "..err)
end
local function custom(str) end
-- Adding new functions to the 'string' table makes them accessible as methods
string.custom = custom
test(string.custom == custom, "custom string function")
test(xpcall(function()
assert(("foo").custom == custom)
end, callback), "custom string method")
string.custom = nil
-- Overriding functions in the 'string' table also overrides methods
do
local reverse = string.reverse
string.reverse = custom
test(string.reverse == custom, "overridden string function")
test(xpcall(function()
assert(("foo").reverse == custom)
end, callback), "overridden string method")
string.reverse = reverse
end
-- If you replace the 'string' table outright, Lua will not switch to it
do
local oldstring = string
string = {
custom = custom
}
test(xpcall(function()
assert(string.custom == custom)
assert(("foo").custom ~= custom)
end, callback), "replaced string table")
string = oldstring
end
-- If you sandbox it though, it will still use the parent environment's 'string' table
local function func()
assert(string.custom == custom)
assert(("foo").custom ~= custom)
end
setfenv(func, {
assert = assert,
string = {
custom = custom
}
})
test(xpcall(func, callback), "sandboxed string method")
-- Lua won't use a local 'string' table
do
local string = {
custom = custom
}
test(xpcall(function()
assert(string.custom == custom)
assert(("foo").custom ~= custom)
end, callback), "local string table")
end
print(prefix..(i == j and "PASSED" or "FAILED")..": passed "..i.."/"..k.." tests")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment