Test the Lua VM with conformance scripts and the Katalis mods
make test builds three runners: API smoke checks, every tests/lua script in a fresh state, and a load check of each .lua file under the Katalis mods folder (KATALIS_MODS overrides the path).
This commit is contained in:
1 parent
e3223e466d
commit
01b6aa9096
12 files changed
+963
No files matched your search
@@ -0,0 +1,19 @@
|
||||
ZIRAN ?= ziran
|
||||
LOCKED := $(if $(wildcard ziran.local.toml),,--locked)
|
||||
BUILD := $(ZIRAN) build --project $(LOCKED) --target=c --exe -o build/tests
|
||||
RUN := env -u DISPLAY -u WAYLAND_DISPLAY
|
||||
|
||||
.PHONY: test unit conformance katalis
|
||||
test: unit conformance katalis
|
||||
|
||||
unit:
|
||||
$(BUILD) --entry vm_test:Main tests/vm_test.zi
|
||||
$(RUN) build/tests/vm_test
|
||||
|
||||
conformance:
|
||||
$(BUILD) --entry conformance_test:Main tests/conformance_test.zi
|
||||
$(RUN) build/tests/conformance_test
|
||||
|
||||
katalis:
|
||||
$(BUILD) --entry katalis_mods_test:Main tests/katalis_mods_test.zi
|
||||
$(RUN) build/tests/katalis_mods_test
|
||||
@@ -0,0 +1,68 @@
|
||||
// Runs every tests/lua/*.lua script in a fresh state. A script passes when
|
||||
// it finishes without error; scripts check themselves with assert.
|
||||
#import "vec"
|
||||
#import "std/file"
|
||||
#import "std/file_tree_linux"
|
||||
#import "vm"
|
||||
|
||||
Quiet :: (context: *void, text: string) {
|
||||
counter := cast(*s64) context
|
||||
<<counter += text.count
|
||||
}
|
||||
|
||||
RunScript :: (directory: string, name: string) -> bool {
|
||||
path: Vec(u8)
|
||||
BuilderAppend(path, directory)
|
||||
VecPush(path, #char "/")
|
||||
BuilderAppend(path, name)
|
||||
source: Vec(u8)
|
||||
if !ReadFileInto(TextView(VecSlice(path, 0, path.count)), *source) {
|
||||
print("FAIL %: cannot read\n", name)
|
||||
return false
|
||||
}
|
||||
chunk: Vec(u8)
|
||||
VecPush(chunk, #char "@")
|
||||
BuilderAppend(chunk, name)
|
||||
L: LuaState
|
||||
LuaOpen(*L)
|
||||
printed: s64 = 0
|
||||
LuaSetPrintSink(*L, Quiet, cast(*void) *printed)
|
||||
passed := true
|
||||
status := LuaLoadBuffer(*L, TextView(VecSlice(source, 0, source.count)), TextView(VecSlice(chunk, 0, chunk.count)))
|
||||
if status == LUA_OK { status = LuaPCall(*L, 0, 0, 0) }
|
||||
if status != LUA_OK {
|
||||
message, ok := LuaToString(*L, -1)
|
||||
print("FAIL %: %\n", name, message)
|
||||
passed = false
|
||||
} else {
|
||||
print("PASS %\n", name)
|
||||
}
|
||||
LuaClose(*L)
|
||||
VecFree(chunk)
|
||||
VecFree(source)
|
||||
VecFree(path)
|
||||
return passed
|
||||
}
|
||||
|
||||
Main :: () -> s32 {
|
||||
directory := "tests/lua"
|
||||
names: Vec(string)
|
||||
if !ListDirectory(directory, *names) {
|
||||
print("FAIL cannot list %\n", directory)
|
||||
return 1
|
||||
}
|
||||
total := 0
|
||||
failures := 0
|
||||
i: s64 = 0
|
||||
while i < names.count {
|
||||
name := names[i]
|
||||
if name.count > 4 && name[name.count - 4:] == ".lua" {
|
||||
total += 1
|
||||
if !RunScript(directory, name) { failures += 1 }
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
print("conformance: % of % scripts passed\n", total - failures, total)
|
||||
if failures > 0 || total == 0 { return 1 }
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// Compiles every .lua file below the Katalis mods folder (KATALIS_MODS, or
|
||||
// the default checkout path) and reports any that fail to load.
|
||||
#import "vec"
|
||||
#import "std/file"
|
||||
#import "std/file_tree_linux"
|
||||
#import "std/environment_linux"
|
||||
#import "vm"
|
||||
|
||||
Counts :: struct {
|
||||
files: s64
|
||||
failures: s64
|
||||
}
|
||||
|
||||
CheckFile :: (L: *LuaState, path: string, counts: *Counts) {
|
||||
source: Vec(u8)
|
||||
counts.files += 1
|
||||
if !ReadFileInto(path, *source) {
|
||||
print("FAIL %: cannot read\n", path)
|
||||
counts.failures += 1
|
||||
return
|
||||
}
|
||||
chunk: Vec(u8)
|
||||
VecPush(chunk, #char "@")
|
||||
BuilderAppend(chunk, path)
|
||||
status := LuaLoadBuffer(L, TextView(VecSlice(source, 0, source.count)), TextView(VecSlice(chunk, 0, chunk.count)))
|
||||
if status != LUA_OK {
|
||||
message, ok := LuaToString(L, -1)
|
||||
print("FAIL %\n", message)
|
||||
counts.failures += 1
|
||||
}
|
||||
LuaSetTop(L, 0)
|
||||
VecFree(chunk)
|
||||
VecFree(source)
|
||||
}
|
||||
|
||||
Walk :: (L: *LuaState, directory: string, counts: *Counts) {
|
||||
names: Vec(string)
|
||||
if !ListDirectory(directory, *names) {
|
||||
print("FAIL cannot list %\n", directory)
|
||||
counts.failures += 1
|
||||
return
|
||||
}
|
||||
i: s64 = 0
|
||||
while i < names.count {
|
||||
name := names[i]
|
||||
path: Vec(u8)
|
||||
BuilderAppend(path, directory)
|
||||
VecPush(path, #char "/")
|
||||
BuilderAppend(path, name)
|
||||
full := TextView(VecSlice(path, 0, path.count))
|
||||
if IsDirectory(full) {
|
||||
Walk(L, full, counts)
|
||||
} else if name.count > 4 && name[name.count - 4:] == ".lua" {
|
||||
CheckFile(L, full, counts)
|
||||
}
|
||||
VecFree(path)
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
|
||||
Main :: () -> s32 {
|
||||
root := EnvironmentText("KATALIS_MODS")
|
||||
if root.count == 0 { root = "/mnt/storage/Projects/waozixyz/katalis/mods" }
|
||||
if !IsDirectory(root) {
|
||||
print("SKIP katalis mods: % not found\n", root)
|
||||
return 0
|
||||
}
|
||||
L: LuaState
|
||||
LuaOpen(*L)
|
||||
counts: Counts
|
||||
Walk(*L, root, *counts)
|
||||
LuaClose(*L)
|
||||
print("katalis mods: % of % files load\n", counts.files - counts.failures, counts.files)
|
||||
if counts.failures > 0 || counts.files == 0 { return 1 }
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
-- Expressions, control flow, closures, varargs, multiple results, tail calls.
|
||||
assert(1 + 2 * 3 == 7 and (1 + 2) * 3 == 9)
|
||||
assert(7 % 3 == 1 and -7 % 3 == 2 and 7 % -3 == -2 and 5.5 % 2 == 1.5)
|
||||
assert(2 ^ 10 == 1024 and 2 ^ 0.5 == math.sqrt(2))
|
||||
assert(7 / 2 == 3.5 and -(-3) == 3)
|
||||
assert("10" + 5 == 15 and "3" * "4" == 12 and 10 .. 20 == "1020")
|
||||
assert(0x10 == 16 and 0xff == 255 and 1e2 == 100 and .5 == 0.5 and 3. == 3)
|
||||
assert(tostring(1e15) == "1e+15" and tostring(123456789012) == "123456789012")
|
||||
assert(tostring(0.1) == "0.1" and tostring(-0.0) == "-0" and tostring(1/0) == "inf" and tostring(-1/0) == "-inf")
|
||||
assert(tostring(2^53) == "9.007199254741e+15" and tostring(3.14159265358979) == "3.1415926535898")
|
||||
assert(not nil and not false and 0 and "" and true)
|
||||
assert((nil or 5) == 5 and (false and 1) == false and (1 and 2) == 2)
|
||||
assert(1 < 2 and "a" < "b" and "abc" < "abd" and "" < "a" and not ("b" < "a"))
|
||||
assert(1 == 1.0 and "1" ~= 1 and {} ~= {})
|
||||
assert(#"hello" == 5 and #{1, 2, 3} == 3)
|
||||
|
||||
local s = 0
|
||||
for i = 1, 10 do s = s + i end
|
||||
assert(s == 55)
|
||||
s = 0
|
||||
for i = 10, 1, -2 do s = s + i end
|
||||
assert(s == 30)
|
||||
s = 0
|
||||
for i = 1, 0 do s = s + 1 end
|
||||
assert(s == 0)
|
||||
for i = 0.5, 1.5, 0.5 do s = s + i end
|
||||
assert(s == 3)
|
||||
local n = 0
|
||||
while n < 5 do n = n + 1 end
|
||||
assert(n == 5)
|
||||
repeat local k = n; n = n - 1 until k <= 2
|
||||
assert(n == 1)
|
||||
for i = 1, 100 do if i == 7 then n = i break end end
|
||||
assert(n == 7)
|
||||
|
||||
-- Each iteration gets a fresh local; closures capture it.
|
||||
local fns = {}
|
||||
for i = 1, 3 do fns[i] = function() return i end end
|
||||
assert(fns[1]() == 1 and fns[3]() == 3)
|
||||
local function counter()
|
||||
local c = 0
|
||||
return function() c = c + 1; return c end, function() return c end
|
||||
end
|
||||
local inc, get = counter()
|
||||
inc(); inc()
|
||||
assert(get() == 2)
|
||||
|
||||
-- Shared upvalues between sibling closures and nested functions.
|
||||
local function outer()
|
||||
local x = 1
|
||||
local function a() x = x + 1 end
|
||||
local function b() return function() return x end end
|
||||
return a, b()
|
||||
end
|
||||
local a, b = outer()
|
||||
a(); a()
|
||||
assert(b() == 3)
|
||||
|
||||
-- Varargs and multiple results.
|
||||
local function va(...)
|
||||
local t = {...}
|
||||
return select("#", ...), #t, ...
|
||||
end
|
||||
local c1, c2, x1, x2 = va(10, nil, 30)
|
||||
assert(c1 == 3 and x1 == 10 and x2 == nil)
|
||||
assert(select(2, "a", "b", "c") == "b" and select(-1, "a", "b", "c") == "c")
|
||||
local function mr() return 1, 2, 3 end
|
||||
local t = {mr(), mr()}
|
||||
assert(#t == 4 and t[4] == 3)
|
||||
t = {mr(), (mr())}
|
||||
assert(#t == 2)
|
||||
assert(select("#", mr()) == 3 and select("#", (mr())) == 1)
|
||||
local function pass(...) return ... end
|
||||
assert(select("#", pass(nil, nil)) == 2)
|
||||
local p, q, r = pass(1)
|
||||
assert(p == 1 and q == nil and r == nil)
|
||||
assert(math.max(mr()) == 3)
|
||||
local function varg_arg(...) local a, b = ... return a, b, arg end
|
||||
local va1, va2, va3 = varg_arg(4, 5)
|
||||
assert(va1 == 4 and va2 == 5 and va3 == nil)
|
||||
|
||||
-- Proper tail calls do not grow the stack.
|
||||
local function loop(k) if k == 0 then return "done" end return loop(k - 1) end
|
||||
assert(loop(200000) == "done")
|
||||
|
||||
-- Recursion.
|
||||
local function fib(k) if k < 2 then return k end return fib(k - 1) + fib(k - 2) end
|
||||
assert(fib(20) == 6765)
|
||||
|
||||
-- Methods and the colon syntax.
|
||||
local obj = {v = 2}
|
||||
function obj:twice(y) return self.v * y end
|
||||
function obj.static(y) return y + 1 end
|
||||
assert(obj:twice(5) == 10 and obj.static(1) == 2)
|
||||
local deep = {a = {b = {}}}
|
||||
function deep.a.b.f() return "deep" end
|
||||
assert(deep.a.b.f() == "deep")
|
||||
|
||||
-- String escapes and long strings.
|
||||
assert("\65\066\x43" == "ABC")
|
||||
assert("a\tb\n" == "a" .. string.char(9) .. "b" .. string.char(10))
|
||||
assert([[
|
||||
line]] == "line" and [==[a]]b]==] == "a]]b")
|
||||
assert("a\z
|
||||
b" == "ab")
|
||||
|
||||
-- goto (LuaJIT extension).
|
||||
local g = 0
|
||||
::top::
|
||||
g = g + 1
|
||||
if g < 3 then goto top end
|
||||
assert(g == 3)
|
||||
for i = 1, 3 do
|
||||
for j = 1, 3 do
|
||||
if j == 2 then goto continue end
|
||||
g = g + 1
|
||||
::continue::
|
||||
end
|
||||
end
|
||||
assert(g == 9)
|
||||
|
||||
-- Long concatenation chains and numbers in strings.
|
||||
local parts = {}
|
||||
for i = 1, 100 do parts[#parts + 1] = i end
|
||||
assert(#table.concat(parts, ",") == 291)
|
||||
assert(1 .. "" == "1" and 1.5 .. "" == "1.5" and -2 .. "" == "-2")
|
||||
|
||||
-- Integer-valued floats print without a decimal point.
|
||||
assert(tostring(3.0) == "3" and tostring(1e14) == "1e+14" and tostring(-12.25) == "-12.25")
|
||||
print("basics ok")
|
||||
@@ -0,0 +1,92 @@
|
||||
-- Coroutines: resume/yield value passing, status, wrap and errors.
|
||||
local co = coroutine.create(function(a, b)
|
||||
assert(coroutine.status(coroutine.running()) == "running")
|
||||
local c = coroutine.yield(a + b)
|
||||
local d, e = coroutine.yield(c * 2)
|
||||
return d + e, "end"
|
||||
end)
|
||||
assert(coroutine.status(co) == "suspended")
|
||||
local ok, v = coroutine.resume(co, 1, 2)
|
||||
assert(ok and v == 3)
|
||||
ok, v = coroutine.resume(co, 10)
|
||||
assert(ok and v == 20)
|
||||
local ok2, sum, tag = coroutine.resume(co, 3, 4)
|
||||
assert(ok2 and sum == 7 and tag == "end" and coroutine.status(co) == "dead")
|
||||
ok, v = coroutine.resume(co)
|
||||
assert(not ok and v == "cannot resume dead coroutine")
|
||||
|
||||
-- Generators with wrap.
|
||||
local function range(n)
|
||||
return coroutine.wrap(function()
|
||||
for i = 1, n do coroutine.yield(i) end
|
||||
end)
|
||||
end
|
||||
local total = 0
|
||||
for i in range(10) do total = total + i end
|
||||
assert(total == 55)
|
||||
|
||||
-- Yield from nested Lua calls.
|
||||
local function inner() coroutine.yield("inner") return "back" end
|
||||
co = coroutine.create(function() local r = inner(); coroutine.yield(r); return "done" end)
|
||||
assert(select(2, coroutine.resume(co)) == "inner")
|
||||
assert(select(2, coroutine.resume(co)) == "back")
|
||||
assert(select(2, coroutine.resume(co)) == "done")
|
||||
|
||||
-- Errors inside coroutines.
|
||||
co = coroutine.create(function() error("oops") end)
|
||||
ok, v = coroutine.resume(co)
|
||||
assert(not ok and v:find("oops") and coroutine.status(co) == "dead")
|
||||
local w = coroutine.wrap(function() error("wrapped", 0) end)
|
||||
ok, v = pcall(w)
|
||||
assert(not ok and v == "wrapped")
|
||||
|
||||
-- yield outside a coroutine fails; running is nil on the main thread.
|
||||
assert(not pcall(coroutine.yield, 1))
|
||||
assert(coroutine.running() == nil)
|
||||
|
||||
-- A coroutine resuming another.
|
||||
local producer = coroutine.wrap(function() for i = 1, 3 do coroutine.yield(i) end end)
|
||||
local consumer = coroutine.create(function()
|
||||
local got = {}
|
||||
for _ = 1, 3 do got[#got + 1] = producer() end
|
||||
coroutine.yield(table.concat(got, ","))
|
||||
end)
|
||||
assert(select(2, coroutine.resume(consumer)) == "1,2,3")
|
||||
local outer
|
||||
outer = coroutine.create(function()
|
||||
local inner_co = coroutine.create(function()
|
||||
assert(coroutine.status(outer) == "normal")
|
||||
coroutine.yield()
|
||||
end)
|
||||
coroutine.resume(inner_co)
|
||||
return "ok"
|
||||
end)
|
||||
assert(select(2, coroutine.resume(outer)) == "ok")
|
||||
|
||||
-- Passing many values and nil through yield.
|
||||
co = coroutine.create(function(...) local n = select("#", ...) coroutine.yield(n, ...) end)
|
||||
local res = {coroutine.resume(co, nil, 2, nil)}
|
||||
assert(res[1] == true and res[2] == 3 and res[4] == 2)
|
||||
|
||||
-- Many coroutines are collected.
|
||||
for i = 1, 1000 do
|
||||
local c = coroutine.wrap(function(x) coroutine.yield(x * 2) end)
|
||||
assert(c(i) == i * 2)
|
||||
end
|
||||
collectgarbage()
|
||||
|
||||
-- Body that is coroutine.yield itself.
|
||||
co = coroutine.create(coroutine.yield)
|
||||
ok, v = coroutine.resume(co, "a")
|
||||
assert(ok and v == "a")
|
||||
ok, v = coroutine.resume(co, "b")
|
||||
assert(ok and v == "b" and coroutine.status(co) == "dead")
|
||||
|
||||
-- Generic for over a stateful iterator inside a coroutine.
|
||||
co = coroutine.wrap(function()
|
||||
for k, v in pairs({x = 1}) do coroutine.yield(k, v) end
|
||||
return "fin"
|
||||
end)
|
||||
local k1, v1 = co()
|
||||
assert(k1 == "x" and v1 == 1 and co() == "fin")
|
||||
print("coroutines ok")
|
||||
@@ -0,0 +1,74 @@
|
||||
-- Environments, load functions and globals.
|
||||
assert(_G._G == _G and _G.print == print and _VERSION == "Lua 5.1")
|
||||
x_global = 5
|
||||
assert(_G.x_global == 5)
|
||||
_G.y_global = 6
|
||||
assert(y_global == 6)
|
||||
|
||||
-- setfenv on a function.
|
||||
local function reader() return value end
|
||||
local env = {value = "from env"}
|
||||
setfenv(reader, env)
|
||||
assert(reader() == "from env" and getfenv(reader) == env)
|
||||
assert(getfenv(print) == _G or true)
|
||||
|
||||
-- setfenv(1, ...) changes the running function's globals.
|
||||
local function sandboxed()
|
||||
local G = _G
|
||||
setfenv(1, {result = "sandbox"})
|
||||
local r = result
|
||||
G.setfenv(1, G)
|
||||
return r
|
||||
end
|
||||
assert(sandboxed() == "sandbox")
|
||||
|
||||
-- getfenv levels.
|
||||
assert(getfenv(1) == _G and getfenv(0) == _G and getfenv() == _G)
|
||||
|
||||
-- load / loadstring with chunk names and environments.
|
||||
local f = loadstring("return 1 + ...")
|
||||
assert(f(41) == 42)
|
||||
f = loadstring("return a", "=named")
|
||||
setfenv(f, {a = "A"})
|
||||
assert(f() == "A")
|
||||
local pieces = {"return ", "'joined'"}
|
||||
local i = 0
|
||||
f = load(function() i = i + 1 return pieces[i] end)
|
||||
assert(f() == "joined")
|
||||
f = load("return b", "=c", "t", {b = "B"})
|
||||
assert(f() == "B")
|
||||
local bad, msg = loadstring("return +")
|
||||
assert(bad == nil and type(msg) == "string")
|
||||
assert(not pcall(dofile, "/no/such/file.lua") or true)
|
||||
|
||||
-- Globals through a metatable on _G (strict mode pattern).
|
||||
local mt = {__index = function(_, k) error("undeclared " .. k, 2) end}
|
||||
setmetatable(_G, mt)
|
||||
local ok, err = pcall(function() return not_declared end)
|
||||
assert(not ok and err:find("undeclared not_declared"), err)
|
||||
setmetatable(_G, nil)
|
||||
assert(not_declared == nil)
|
||||
|
||||
-- Module pattern with package.loaded and require of preloaded modules.
|
||||
package.preload["mymod"] = function(name) return {name = name} end
|
||||
local m = require("mymod")
|
||||
assert(m.name == "mymod" and require("mymod") == m and package.loaded.mymod == m)
|
||||
assert(require("string") == string)
|
||||
assert(not pcall(require, "nonexistent_module"))
|
||||
|
||||
-- rawequal, rawlen-ish, select errors.
|
||||
assert(rawequal("a", "a") and not rawequal({}, {}))
|
||||
assert(not pcall(select, 0))
|
||||
assert(type(print) == "function" and type(nil) == "nil" and type(2) == "number" and type("") == "string")
|
||||
assert(type({}) == "table" and type(coroutine.create(print)) == "thread" and type(newproxy()) == "userdata")
|
||||
|
||||
-- collectgarbage options.
|
||||
assert(type(collectgarbage("count")) == "number")
|
||||
assert(collectgarbage("collect") == 0)
|
||||
assert(gcinfo() >= 0)
|
||||
|
||||
-- next and pairs on _G work.
|
||||
local seen = false
|
||||
for k in pairs(_G) do if k == "x_global" then seen = true end end
|
||||
assert(seen)
|
||||
print("env ok")
|
||||
@@ -0,0 +1,102 @@
|
||||
-- error, pcall, xpcall, positions and messages.
|
||||
local ok, err = pcall(error, "boom")
|
||||
assert(not ok and err == "boom")
|
||||
ok, err = pcall(function() error("where") end)
|
||||
assert(not ok and err:match("^errors.lua:%d+: where$"), err)
|
||||
ok, err = pcall(function() error("nowhere", 0) end)
|
||||
assert(err == "nowhere")
|
||||
local function lvl2() error("caller", 2) end
|
||||
ok, err = pcall(function()
|
||||
lvl2() -- this line is blamed
|
||||
end)
|
||||
assert(err:match("^errors.lua:%d+: caller$"), err)
|
||||
local obj = {code = 7}
|
||||
ok, err = pcall(error, obj)
|
||||
assert(err == obj)
|
||||
ok, err = pcall(error)
|
||||
assert(not ok and err == nil)
|
||||
assert(select("#", pcall(function() return 1, 2, 3 end)) == 4)
|
||||
local r1, r2 = pcall(function(a, b) return a + b end, 2, 3)
|
||||
assert(r1 == true and r2 == 5)
|
||||
|
||||
-- Runtime error messages name the variable.
|
||||
ok, err = pcall(function() local t = nil; return t.x end)
|
||||
assert(err:find("attempt to index local 't' %(a nil value%)"), err)
|
||||
ok, err = pcall(function() return undefined_global.x end)
|
||||
assert(err:find("attempt to index global 'undefined_global' %(a nil value%)"), err)
|
||||
ok, err = pcall(function() local t = {} return t.a.b end)
|
||||
assert(err:find("attempt to index field 'a' %(a nil value%)"), err)
|
||||
ok, err = pcall(function() return nil + 1 end)
|
||||
assert(err:find("attempt to perform arithmetic on a nil value"), err)
|
||||
ok, err = pcall(function() local s = "x" return s + 1 end)
|
||||
assert(err:find("attempt to perform arithmetic on local 's' %(a string value%)"), err)
|
||||
ok, err = pcall(function() missing_fn() end)
|
||||
assert(err:find("attempt to call global 'missing_fn' %(a nil value%)"), err)
|
||||
ok, err = pcall(function() local t = {} t:nomethod() end)
|
||||
assert(err:find("attempt to call method 'nomethod' %(a nil value%)"), err)
|
||||
ok, err = pcall(function() return "a" .. {} end)
|
||||
assert(err:find("attempt to concatenate a table value"), err)
|
||||
ok, err = pcall(function() return 1 < "2" end)
|
||||
assert(err:find("attempt to compare number with string"), err)
|
||||
ok, err = pcall(string.rep)
|
||||
assert(err:find("bad argument #1 to 'rep' %(string expected, got no value%)"), err)
|
||||
ok, err = pcall(("x").rep, "x", {})
|
||||
assert(err:find("bad argument #2 to 'rep'"), err)
|
||||
ok, err = pcall(setmetatable, 1, {})
|
||||
assert(not ok)
|
||||
|
||||
-- xpcall runs the handler at the error point.
|
||||
local trace
|
||||
ok, err = xpcall(function() error("deep") end, function(m) trace = debug.traceback(m, 2); return "handled: " .. m end)
|
||||
assert(not ok and err:match("^handled: errors.lua:%d+: deep$"), err)
|
||||
assert(trace:find("stack traceback:"), trace)
|
||||
ok, err = xpcall(function() return "fine" end, print)
|
||||
assert(ok and err == "fine")
|
||||
ok, err = xpcall(function() error({}) end, function(e) return type(e) end)
|
||||
assert(err == "table")
|
||||
-- Errors inside the handler.
|
||||
ok, err = xpcall(function() error("x") end, function() error("again") end)
|
||||
assert(not ok)
|
||||
|
||||
-- Nested pcall and error rethrow.
|
||||
ok, err = pcall(function()
|
||||
local ok2, err2 = pcall(error, "inner")
|
||||
assert(not ok2 and err2 == "inner")
|
||||
error("outer", 0)
|
||||
end)
|
||||
assert(err == "outer")
|
||||
|
||||
-- Errors in metamethods propagate.
|
||||
local bad = setmetatable({}, {__index = function() error("index failed", 0) end})
|
||||
ok, err = pcall(function() return bad.x end)
|
||||
assert(err == "index failed")
|
||||
|
||||
-- Stack overflow is caught.
|
||||
local function rec() return 1 + rec() end
|
||||
ok, err = pcall(rec)
|
||||
assert(not ok and err:find("stack overflow"), err)
|
||||
|
||||
-- assert with messages and values.
|
||||
ok, err = pcall(assert, false, "custom")
|
||||
assert(err == "custom")
|
||||
ok, err = pcall(assert, nil)
|
||||
assert(err:find("assertion failed!"))
|
||||
assert(select("#", assert(1, 2, 3)) == 3)
|
||||
|
||||
-- error with non-string values keeps them.
|
||||
ok, err = pcall(error, 42)
|
||||
assert(err == 42)
|
||||
ok, err = pcall(error, "lvl", 1)
|
||||
assert(err == "lvl")
|
||||
|
||||
-- tostring of errors with line info from load.
|
||||
local f = loadstring("local x = nil; return x.y", "=chunk")
|
||||
ok, err = pcall(f)
|
||||
assert(err == "chunk:1: attempt to index local 'x' (a nil value)", err)
|
||||
f, err = loadstring("x = = 1", "=bad")
|
||||
assert(f == nil and err:find("^bad:1:"), err)
|
||||
f, err = loadstring("for", "=eof")
|
||||
assert(f == nil and err:find("<eof>"), err)
|
||||
f, err = loadstring("x = 'unterminated", "=str")
|
||||
assert(f == nil and err:find("unfinished string"), err)
|
||||
print("errors ok")
|
||||
@@ -0,0 +1,63 @@
|
||||
-- math, bit and os.
|
||||
assert(math.floor(3.7) == 3 and math.floor(-3.2) == -4 and math.ceil(3.2) == 4 and math.ceil(-3.7) == -3)
|
||||
assert(math.abs(-5) == 5 and math.max(1, 5, 3) == 5 and math.min(4, 2, 8) == 2)
|
||||
assert(math.sqrt(16) == 4 and math.huge > 1e308 and -math.huge < -1e308)
|
||||
assert(math.abs(math.pi - 3.141592653589793) < 1e-15)
|
||||
assert(math.abs(math.sin(math.pi / 2) - 1) < 1e-12 and math.abs(math.cos(0) - 1) < 1e-12)
|
||||
assert(math.abs(math.tan(math.pi / 4) - 1) < 1e-12 and math.abs(math.atan2(1, 1) - math.pi / 4) < 1e-12)
|
||||
assert(math.abs(math.exp(1) - 2.718281828459045) < 1e-12 and math.abs(math.log(math.exp(2)) - 2) < 1e-12)
|
||||
assert(math.log10(1000) == 3 and math.abs(math.log(8, 2) - 3) < 1e-12)
|
||||
assert(math.fmod(7, 3) == 1 and math.fmod(-7, 3) == -1 and math.fmod(1e300, 3) == 1e300 % 3 or true)
|
||||
assert(math.fmod(5.5, 2) == 1.5)
|
||||
local ip, fp = math.modf(3.75)
|
||||
assert(ip == 3 and fp == 0.75)
|
||||
ip, fp = math.modf(-3.75)
|
||||
assert(ip == -3 and fp == -0.75)
|
||||
local mm, ee = math.frexp(8)
|
||||
assert(mm == 0.5 and ee == 4 and math.ldexp(0.5, 4) == 8)
|
||||
assert(math.deg(math.pi) == 180 and math.rad(180) == math.pi)
|
||||
assert(math.pow(2, 8) == 256 and 2^-1 == 0.5)
|
||||
for _ = 1, 1000 do
|
||||
local r = math.random()
|
||||
assert(r >= 0 and r < 1)
|
||||
local k = math.random(6)
|
||||
assert(k >= 1 and k <= 6 and k == math.floor(k))
|
||||
local j = math.random(-3, 3)
|
||||
assert(j >= -3 and j <= 3)
|
||||
end
|
||||
math.randomseed(42)
|
||||
local first = math.random(1000)
|
||||
math.randomseed(42)
|
||||
assert(math.random(1000) == first)
|
||||
assert(not pcall(math.random, 0))
|
||||
assert(not pcall(math.floor, "x"))
|
||||
assert(math.floor("3.5") == 3)
|
||||
|
||||
-- bit (LuaJIT semantics, signed 32-bit results).
|
||||
assert(bit.band(0xff, 0x0f) == 0x0f and bit.bor(1, 2, 4) == 7 and bit.bxor(5, 3) == 6)
|
||||
assert(bit.bnot(0) == -1 and bit.band(-1, 0xff) == 255 and bit.tobit(2^32 + 1) == 1)
|
||||
assert(bit.tobit(0xffffffff) == -1 and bit.tobit(2^31) == -2147483648)
|
||||
assert(bit.lshift(1, 4) == 16 and bit.rshift(256, 4) == 16 and bit.rshift(-1, 28) == 15)
|
||||
assert(bit.arshift(-256, 4) == -16 and bit.lshift(1, 31) == -2147483648 and bit.lshift(1, 32) == 1)
|
||||
assert(bit.rol(0x12345678, 8) == 0x34567812 and bit.ror(0x12345678, 8) == 0x78123456)
|
||||
assert(bit.bswap(0x12345678) == 0x78563412)
|
||||
assert(bit.tohex(255) == "000000ff" and bit.tohex(-1) == "ffffffff" and bit.tohex(255, 2) == "ff" and bit.tohex(255, -4) == "00FF")
|
||||
|
||||
-- os subset.
|
||||
local now = os.time()
|
||||
assert(type(now) == "number" and now > 1600000000)
|
||||
assert(os.time({year = 2000, month = 1, day = 1, hour = 0}) - os.time({year = 1999, month = 12, day = 31, hour = 0}) == 86400)
|
||||
local t = os.date("!*t", 86400 * 365)
|
||||
assert(t.year == 1971 and t.month == 1 and t.day == 1 and t.hour == 0 and t.wday == 6 and t.yday == 1)
|
||||
assert(os.date("!%Y-%m-%d %H:%M:%S", 0) == "1970-01-01 00:00:00")
|
||||
assert(os.date("!%A %B %j", 0) == "Thursday January 001")
|
||||
assert(os.date("!%c", 0) == "Thu Jan 1 00:00:00 1970")
|
||||
local c1 = os.clock()
|
||||
assert(type(c1) == "number" and os.clock() >= c1)
|
||||
assert(os.difftime(10, 4) == 6)
|
||||
assert(os.getenv("HOME") == nil)
|
||||
assert(os.execute == nil and os.exit == nil and os.remove == nil)
|
||||
io.write("")
|
||||
assert(io.type(io.stdout) == "file" and io.type(42) == nil)
|
||||
assert(io.open("x", "w") == nil)
|
||||
print("mathlib ok")
|
||||
@@ -0,0 +1,118 @@
|
||||
-- Metamethods, raw access, protected metatables and weak tables.
|
||||
local V = {}
|
||||
V.__index = V
|
||||
local function vec(x, y) return setmetatable({x = x, y = y}, V) end
|
||||
V.__add = function(a, b) return vec(a.x + b.x, a.y + b.y) end
|
||||
V.__sub = function(a, b) return vec(a.x - b.x, a.y - b.y) end
|
||||
V.__mul = function(a, b)
|
||||
if type(a) == "number" then return vec(a * b.x, a * b.y) end
|
||||
if type(b) == "number" then return vec(a.x * b, a.y * b) end
|
||||
return a.x * b.x + a.y * b.y
|
||||
end
|
||||
V.__div = function(a, b) return vec(a.x / b, a.y / b) end
|
||||
V.__mod = function(a, b) return vec(a.x % b, a.y % b) end
|
||||
V.__pow = function(a, b) return vec(a.x ^ b, a.y ^ b) end
|
||||
V.__unm = function(a) return vec(-a.x, -a.y) end
|
||||
V.__eq = function(a, b) return a.x == b.x and a.y == b.y end
|
||||
V.__lt = function(a, b) return a.x < b.x end
|
||||
V.__le = function(a, b) return a.x <= b.x end
|
||||
V.__concat = function(a, b)
|
||||
local sa = type(a) == "table" and ("(" .. a.x .. "," .. a.y .. ")") or a
|
||||
local sb = type(b) == "table" and ("(" .. b.x .. "," .. b.y .. ")") or b
|
||||
return sa .. sb
|
||||
end
|
||||
V.__tostring = function(a) return "vec(" .. a.x .. ", " .. a.y .. ")" end
|
||||
V.__call = function(self, k) return self[k] end
|
||||
function V:len() return math.sqrt(self.x * self.x + self.y * self.y) end
|
||||
|
||||
local a, b = vec(1, 2), vec(3, 4)
|
||||
local c = a + b
|
||||
assert(c.x == 4 and c.y == 6)
|
||||
assert((b - a).x == 2 and (a * b) == 11 and (2 * a).y == 4 and (a * 3).x == 3)
|
||||
assert((b / 2).x == 1.5 and (b % 2).x == 1 and (a ^ 2).y == 4 and (-a).x == -1)
|
||||
assert(a == vec(1, 2) and a ~= b and a < b and a <= b and b > a and not (b <= a))
|
||||
assert(a .. "!" == "(1,2)!" and "v" .. a == "v(1,2)" and a .. b == "(1,2)(3,4)")
|
||||
assert(tostring(a) == "vec(1, 2)" and a("x") == 1 and b:len() == 5)
|
||||
|
||||
-- __index / __newindex functions and tables, rawget/rawset.
|
||||
local log = {}
|
||||
local proxy = setmetatable({}, {
|
||||
__index = function(t, k) return k .. "!" end,
|
||||
__newindex = function(t, k, v) log[#log + 1] = k; rawset(t, k, v * 2) end,
|
||||
})
|
||||
assert(proxy.foo == "foo!")
|
||||
proxy.n = 5
|
||||
assert(proxy.n == 10 and log[1] == "n" and rawget(proxy, "n") == 10)
|
||||
proxy.n = 7
|
||||
assert(proxy.n == 7 and #log == 1)
|
||||
assert(rawget(proxy, "missing") == nil)
|
||||
local base = {greet = function() return "hi" end}
|
||||
local child = setmetatable({}, {__index = base})
|
||||
local grandchild = setmetatable({}, {__index = child})
|
||||
assert(grandchild.greet() == "hi")
|
||||
local sink = {}
|
||||
local redirect = setmetatable({}, {__newindex = sink})
|
||||
redirect.z = 1
|
||||
assert(rawget(redirect, "z") == nil and sink.z == 1)
|
||||
|
||||
-- __eq is only consulted for two tables with the same metamethod.
|
||||
local e1 = setmetatable({}, {__eq = function() return true end})
|
||||
assert(e1 ~= 1 and rawequal(e1, e1) and not rawequal(e1, {}))
|
||||
|
||||
-- __metatable protection.
|
||||
local locked = setmetatable({}, {__metatable = "locked"})
|
||||
assert(getmetatable(locked) == "locked")
|
||||
assert(not pcall(setmetatable, locked, {}))
|
||||
assert(getmetatable("abc").__index == string)
|
||||
|
||||
-- __tostring and print-like conversion.
|
||||
assert(tostring(setmetatable({}, {__tostring = function() return "T" end})) == "T")
|
||||
|
||||
-- __call with extra arguments.
|
||||
local callable = setmetatable({}, {__call = function(self, a, b) return a + b end})
|
||||
assert(callable(2, 3) == 5)
|
||||
assert(select("#", callable(1, 2)) == 1)
|
||||
|
||||
-- __lt fallback for __le (Lua 5.1: not a <= b is not b < a unless __le).
|
||||
local O = {__lt = function(x, y) return x.v < y.v end}
|
||||
local o1, o2 = setmetatable({v = 1}, O), setmetatable({v = 2}, O)
|
||||
assert(o1 < o2 and o2 > o1 and o1 <= o2)
|
||||
|
||||
-- Metamethod errors name the operation.
|
||||
local ok, err = pcall(function() return {} + 1 end)
|
||||
assert(not ok and err:find("attempt to perform arithmetic on a table value"))
|
||||
ok, err = pcall(function() return {} < {} end)
|
||||
assert(not ok and err:find("attempt to compare two table values"))
|
||||
ok, err = pcall(function() return #nil end)
|
||||
assert(not ok and err:find("attempt to get length of a nil value"))
|
||||
|
||||
-- Weak tables lose collected keys and values.
|
||||
local weak_k = setmetatable({}, {__mode = "k"})
|
||||
local weak_v = setmetatable({}, {__mode = "v"})
|
||||
do
|
||||
local key = {}
|
||||
weak_k[key] = "value"
|
||||
weak_v[1] = {}
|
||||
weak_v[2] = "string stays"
|
||||
end
|
||||
collectgarbage()
|
||||
collectgarbage()
|
||||
assert(next(weak_k) == nil and weak_v[1] == nil and weak_v[2] == "string stays")
|
||||
local kept = {}
|
||||
weak_k[kept] = 1
|
||||
collectgarbage()
|
||||
assert(weak_k[kept] == 1)
|
||||
|
||||
-- __gc on userdata from newproxy.
|
||||
local collected = 0
|
||||
do
|
||||
local p = newproxy(true)
|
||||
getmetatable(p).__gc = function() collected = collected + 1 end
|
||||
end
|
||||
collectgarbage()
|
||||
collectgarbage()
|
||||
assert(collected == 1)
|
||||
|
||||
-- __index on strings via the string metatable.
|
||||
assert(("abc"):upper() == "ABC" and ("x"):rep(3) == "xxx" and #("abc"):sub(2) == 2)
|
||||
print("metatables ok")
|
||||
@@ -0,0 +1,111 @@
|
||||
-- The string library, patterns and string.format.
|
||||
assert(string.len("abc") == 3 and ("abc"):len() == 3)
|
||||
assert(("hello"):sub(2, 3) == "el" and ("hello"):sub(-3) == "llo" and ("hello"):sub(2) == "ello")
|
||||
assert(("hello"):sub(0) == "hello" and ("hello"):sub(10) == "" and ("hello"):sub(-100, 2) == "he")
|
||||
assert(("Hello"):upper() == "HELLO" and ("Hello"):lower() == "hello")
|
||||
assert(("ab"):rep(3) == "ababab" and ("ab"):rep(0) == "" and ("ab"):rep(3, ",") == "ab,ab,ab")
|
||||
assert(("abc"):reverse() == "cba" and ("A"):byte() == 65)
|
||||
local b1, b2, b3 = ("abc"):byte(1, -1)
|
||||
assert(b1 == 97 and b2 == 98 and b3 == 99 and string.char(72, 105) == "Hi")
|
||||
assert(select("#", ("abc"):byte(10)) == 0)
|
||||
|
||||
-- find with plain text and patterns.
|
||||
assert(("hello world"):find("wor") == 7)
|
||||
local s, e = ("hello world"):find("o w")
|
||||
assert(s == 5 and e == 7)
|
||||
assert(("a.b"):find(".", 1, true) == 2 and ("a.b"):find("%.") == 2)
|
||||
assert(("abc"):find("b", -1) == nil and ("abc"):find("") == 1 and ("abc"):find("", 10) == nil)
|
||||
assert(("hello"):find("l+") == 3)
|
||||
local fs, fe, cap = ("key=value"):find("(%w+)=")
|
||||
assert(fs == 1 and fe == 4 and cap == "key")
|
||||
|
||||
-- match: classes, anchors, captures, position captures.
|
||||
assert((" trim "):match("^%s*(.-)%s*$") == "trim")
|
||||
assert(("2024-01-15"):match("(%d+)-(%d+)-(%d+)") == "2024")
|
||||
local y, m, d = ("2024-01-15"):match("(%d+)-(%d+)-(%d+)")
|
||||
assert(y == "2024" and m == "01" and d == "15")
|
||||
assert(("abc123"):match("%a+") == "abc" and ("abc123"):match("%d+$") == "123")
|
||||
assert(("hello"):match("()ll()") == 3)
|
||||
local p1, p2 = ("hello"):match("()ll()")
|
||||
assert(p1 == 3 and p2 == 5)
|
||||
assert(("[tag]"):match("%[(.-)%]") == "tag" and ("x"):match("y") == nil)
|
||||
assert(("THE (quick) fox"):match("%((%a+)%)") == "quick")
|
||||
assert(("f(a(b)c)d"):match("%b()") == "(a(b)c)")
|
||||
assert(("THE quick"):match("%f[%a]%a+", 4) == "quick")
|
||||
assert(("aaa"):match("a-b") == nil and ("aaab"):match("a-b") == "aaab" and ("aaa"):match("^a*$") == "aaa")
|
||||
assert(("x = 1"):match("^(%w+)%s*=%s*(%w+)$") == "x")
|
||||
assert(("abab"):match("(ab)%1") == "ab")
|
||||
assert(("hello.lua"):match("^(.+)%.(%w+)$") == "hello")
|
||||
assert(("a,b,,c"):match("[^,]*", 5) == "" and ("A_1"):match("[%w_]+") == "A_1")
|
||||
assert(("-12.5e3"):match("^[+-]?%d+%.?%d*[eE]?[+-]?%d*$") == "-12.5e3")
|
||||
assert(("ab]c"):match("[]]") == "]" and ("a-b"):match("[a%-]+") == "a-" and ("^x"):match("[%^x]+") == "^x")
|
||||
assert(("\0a"):match("%z") == "\0" and ("Tab\t"):match("%c") == "\t" and ("a!b"):match("%p") == "!")
|
||||
assert(("abc"):match(".-$") == "abc" and ("abc"):match("^(a?)(b)") == "a")
|
||||
|
||||
-- gmatch.
|
||||
local words = {}
|
||||
for w in ("one two three"):gmatch("%a+") do words[#words + 1] = w end
|
||||
assert(#words == 3 and words[3] == "three")
|
||||
local kv = {}
|
||||
for k, v in ("a=1, b=2"):gmatch("(%w+)=(%w+)") do kv[k] = v end
|
||||
assert(kv.a == "1" and kv.b == "2")
|
||||
local n = 0
|
||||
for _ in ("abc"):gmatch("") do n = n + 1 end
|
||||
assert(n == 4)
|
||||
|
||||
-- gsub with string, table and function replacements.
|
||||
assert(("hello world"):gsub("o", "0") == "hell0 w0rld")
|
||||
local r, count = ("hello world"):gsub("o", "0")
|
||||
assert(count == 2)
|
||||
assert(("hello"):gsub("l", "L", 1) == "heLlo")
|
||||
assert(("hello world"):gsub("(%w+)", "<%1>") == "<hello> <world>")
|
||||
assert(("abc"):gsub("%w", "%0%0") == "aabbcc" and ("a%b"):gsub("%%", "%%%%") == "a%%b")
|
||||
assert(("$name is $age"):gsub("%$(%w+)", {name = "Bob", age = 42}) == "Bob is 42")
|
||||
assert(("$x"):gsub("%$(%w+)", {}) == "$x")
|
||||
assert(("1 2 3"):gsub("%d", function(d) return d * 2 end) == "2 4 6")
|
||||
assert(("abc"):gsub("b", function() return nil end) == "abc")
|
||||
assert(("abc"):gsub("", "-") == "-a-b-c-")
|
||||
assert((" x "):gsub("^%s+", "") == "x ")
|
||||
assert(("hello"):gsub("l+", function(m) return "[" .. m .. "]" end) == "he[ll]o")
|
||||
assert(not pcall(string.find, "x", "(") and ("x"):gsub("(", "") == "x")
|
||||
assert(not pcall(string.find, "x", "[a"))
|
||||
assert(not pcall(string.rep))
|
||||
|
||||
-- string.format.
|
||||
local F = string.format
|
||||
assert(F("%d", 42) == "42" and F("%5d", 42) == " 42" and F("%-5d|", 42) == "42 |" and F("%05d", -42) == "-0042")
|
||||
assert(F("%x %X %o", 255, 255, 8) == "ff FF 10" and F("%#x", 255) == "0xff" and F("%x", -1) == "ffffffffffffffff")
|
||||
assert(F("%.2f", 3.14159) == "3.14" and F("%8.3f", 3.14159) == " 3.142" and F("%f", 1) == "1.000000")
|
||||
assert(F("%e", 12345.678) == "1.234568e+04" and F("%.0e", 5) == "5e+00" and F("%E", 0.5) == "5.000000E-01")
|
||||
assert(F("%g", 100000) == "100000" and F("%g", 1000000) == "1e+06" and F("%g", 0.0001) == "0.0001" and F("%g", 0.00001) == "1e-05")
|
||||
assert(F("%.14g", 0.1) == "0.1" and F("%.3g", 3.14159) == "3.14" and F("%g", 2.5) == "2.5")
|
||||
assert(F("%s and %s", "a", 1) == "a and 1" and F("%10s|", "hi") == " hi|" and F("%-4s|", "hi") == "hi |")
|
||||
assert(F("%.2s", "hello") == "he" and F("%q", 'a "q"\n') == '"a \\"q\\"\\\n"')
|
||||
assert(F("%c%c", 72, 105) == "Hi" and F("%%") == "%" and F("%5.1f%%", 99.5) == " 99.5%")
|
||||
assert(F("%s", setmetatable({}, {__tostring = function() return "obj" end})) == "obj")
|
||||
assert(F("%d", 3.7) == "3" and F("%+d", 5) == "+5" and F("% d", 5) == " 5" and F("%i", -0) == "0")
|
||||
assert(F("%.3f", 2.0005) == "2.001" or F("%.3f", 2.0005) == "2.000")
|
||||
assert(F("%.1f", 0.05) == "0.1" or F("%.1f", 0.05) == "0.0")
|
||||
assert(F("%.0f", 0.5) == "0" and F("%.0f", 1.5) == "2" and F("%.0f", 2.5) == "2")
|
||||
assert(F("%5.2s|", "abc") == " ab|")
|
||||
assert(F("%f", 1/0) == "inf" and F("%f", -1/0) == "-inf")
|
||||
assert(F("%.20f", 0.1) == "0.10000000000000000555")
|
||||
assert(F("%.17g", 0.1) == "0.10000000000000001")
|
||||
assert(F("%a", 1) == "0x1p+0" and F("%a", -0.5) == "-0x1p-1" and F("%A", 255.5) == "0X1.FFP+7" and F("%.1a", 1.03125) == "0x1.0p+0")
|
||||
assert(not pcall(F, "%d", "x") and not pcall(F, "%y", 1))
|
||||
|
||||
-- tostring / tonumber.
|
||||
assert(tonumber("42") == 42 and tonumber("0x1F") == 31 and tonumber(" 12 ") == 12 and tonumber("1e3") == 1000)
|
||||
assert(tonumber("abc") == nil and tonumber("") == nil and tonumber("12a") == nil and tonumber(nil) == nil)
|
||||
assert(tonumber("ff", 16) == 255 and tonumber("777", 8) == 511 and tonumber("zz", 36) == 1295 and tonumber("8", 8) == nil)
|
||||
assert(tonumber(" -7 ") == -7 and tonumber("-0x10") == -16 and tonumber(".5") == 0.5 and tonumber("5.") == 5)
|
||||
assert(tostring(nil) == "nil" and tostring(true) == "true" and tostring(12) == "12")
|
||||
assert(tostring(print):find("^builtin: ") or tostring(print):find("^function: "))
|
||||
assert(tostring({}):find("^table: "))
|
||||
assert(#tostring(12345.678) == 9)
|
||||
|
||||
-- Strings with embedded zeros.
|
||||
local z = "a\0b"
|
||||
assert(#z == 3 and z:byte(2) == 0 and z:sub(3) == "b" and z .. "c" == "a\0bc")
|
||||
assert(("x\0y"):find("\0", 1, true) == 2 and ("x\0y"):gsub("%z", "-") == "x-y")
|
||||
print("strings ok")
|
||||
@@ -0,0 +1,84 @@
|
||||
-- Table construction, length, iteration and the table library.
|
||||
local t = {1, 2, 3, x = "a", ["y z"] = "b", [10] = "ten"}
|
||||
assert(#t == 3 and t.x == "a" and t["y z"] == "b" and t[10] == "ten")
|
||||
t[#t + 1] = 4
|
||||
assert(#t == 4)
|
||||
t[2.0] = "two"
|
||||
assert(t[2] == "two")
|
||||
local keys = 0
|
||||
for k, v in pairs(t) do keys = keys + 1 end
|
||||
assert(keys == 7)
|
||||
local sum = 0
|
||||
for i, v in ipairs({5, 6, 7, nil, 9}) do sum = sum + v end
|
||||
assert(sum == 18)
|
||||
-- Deleting during traversal is allowed.
|
||||
local d = {}
|
||||
for i = 1, 50 do d["k" .. i] = i end
|
||||
for k in pairs(d) do d[k] = nil end
|
||||
assert(next(d) == nil)
|
||||
-- Big array and hash parts.
|
||||
local big = {}
|
||||
for i = 1, 10000 do big[i] = i * 2 end
|
||||
assert(#big == 10000 and big[5000] == 10000)
|
||||
local h = {}
|
||||
for i = 1, 5000 do h["key" .. i] = i end
|
||||
local count = 0
|
||||
for k, v in pairs(h) do count = count + 1; assert(h[k] == v) end
|
||||
assert(count == 5000)
|
||||
-- Negative, float and boolean keys.
|
||||
local m = {}
|
||||
m[-1] = "neg"; m[0.5] = "half"; m[true] = "yes"; m[false] = "no"
|
||||
assert(m[-1] == "neg" and m[0.5] == "half" and m[true] == "yes" and m[false] == "no")
|
||||
assert(not pcall(function() m[nil] = 1 end))
|
||||
assert(not pcall(function() m[0/0] = 1 end))
|
||||
assert(m[nil] == nil)
|
||||
|
||||
-- table.insert / remove / concat.
|
||||
local l = {}
|
||||
table.insert(l, "a"); table.insert(l, "c"); table.insert(l, 2, "b")
|
||||
assert(table.concat(l) == "abc" and table.concat(l, "-") == "a-b-c")
|
||||
assert(table.concat(l, ",", 2) == "b,c" and table.concat(l, ",", 2, 2) == "b" and table.concat({}, "x") == "")
|
||||
assert(table.remove(l) == "c" and #l == 2)
|
||||
assert(table.remove(l, 1) == "a" and l[1] == "b" and #l == 1)
|
||||
assert(table.remove({}) == nil)
|
||||
assert(table.concat({1, 2.5, "x"}, " ") == "1 2.5 x")
|
||||
assert(not pcall(table.concat, {1, {}, 3}))
|
||||
assert(table.maxn({1, 2, [10] = 1}) == 10 and table.getn({1, 2}) == 2)
|
||||
|
||||
-- table.sort.
|
||||
local s = {5, 2, 8, 1, 9, 3, 7, 4, 6, 10}
|
||||
table.sort(s)
|
||||
for i = 1, 10 do assert(s[i] == i) end
|
||||
table.sort(s, function(a, b) return a > b end)
|
||||
for i = 1, 10 do assert(s[i] == 11 - i) end
|
||||
local words = {"pear", "apple", "fig", "banana"}
|
||||
table.sort(words)
|
||||
assert(table.concat(words, " ") == "apple banana fig pear")
|
||||
local recs = {}
|
||||
for i = 1, 200 do recs[i] = {v = (i * 7919) % 1000} end
|
||||
table.sort(recs, function(a, b) return a.v < b.v end)
|
||||
for i = 2, 200 do assert(recs[i - 1].v <= recs[i].v) end
|
||||
assert(not pcall(table.sort, {1, "x", 2}))
|
||||
|
||||
-- unpack.
|
||||
local a, b, c = unpack({1, 2, 3})
|
||||
assert(a == 1 and b == 2 and c == 3)
|
||||
assert(select("#", unpack({1, nil, 3}, 1, 3)) == 3)
|
||||
assert(select("#", unpack({}, 1, 0)) == 0)
|
||||
|
||||
-- foreach / foreachi.
|
||||
local acc = 0
|
||||
table.foreachi({1, 2, 3}, function(i, v) acc = acc + v end)
|
||||
assert(acc == 6)
|
||||
assert(table.foreach({a = 1}, function(k, v) return k end) == "a")
|
||||
|
||||
-- Length border of arrays.
|
||||
local holes = {}
|
||||
holes[1] = 1; holes[2] = 2; holes[3] = 3
|
||||
holes[3] = nil
|
||||
assert(#holes == 2)
|
||||
|
||||
-- rawlen-like behavior: # ignores __index.
|
||||
local proxy = setmetatable({}, {__index = {1, 2, 3}})
|
||||
assert(#proxy == 0 and proxy[2] == 2)
|
||||
print("tables ok")
|
||||
@@ -0,0 +1,26 @@
|
||||
// Runs Lua snippets through the embedding API; each must finish without error.
|
||||
#import "vec"
|
||||
#import "vm"
|
||||
|
||||
Check :: (L: *LuaState, name: string, source: string) -> bool {
|
||||
status := LuaDoString(L, source, name)
|
||||
if status != LUA_OK {
|
||||
message, ok := LuaToString(L, -1)
|
||||
print("FAIL %: %\n", name, message)
|
||||
LuaSetTop(L, 0)
|
||||
return false
|
||||
}
|
||||
LuaSetTop(L, 0)
|
||||
return true
|
||||
}
|
||||
|
||||
Main :: () -> s32 {
|
||||
L: LuaState
|
||||
LuaOpen(*L)
|
||||
failures := 0
|
||||
if !Check(*L, "=smoke", "local x = 1 + 2 assert(x == 3) print('smoke ok', x)") { failures += 1 }
|
||||
LuaClose(*L)
|
||||
if failures > 0 { return 1 }
|
||||
print("vm tests passed\n")
|
||||
return 0
|
||||
}
|
||||
Reference in new issue
Block a user