更新:添加doString方法及对应的单元测试

This commit is contained in:
2026-04-05 08:19:20 +08:00
parent 14526b8dc2
commit 8f1d409cf5
10 changed files with 337 additions and 146 deletions

View File

@ -1,4 +1,4 @@
package luarunner
package luaRunner
// ==================== FFI底层 ====================
@ -13,6 +13,8 @@ foreign func unload_lib(selfd: CPointer<Unit>, name: CString): Int32
@C
foreign func run(selfd: CPointer<Unit>, path: CString, arg: CString): Int32
@C
foreign func dostring(selfd: CPointer<Unit>,target: CString): Int32
@C
foreign func cleanup(selfd: CPointer<Unit>): Int32
@C
foreign func get_errno(): Int32
@ -212,6 +214,21 @@ public class LuaRunner {
}
return this.cachedResult
}
public func doString(target: String): String
{
let targetptr = toCStr(target);
let code = unsafe { dostring(this.handle, targetptr) }
unsafe{
if(!targetptr.isNull()){LibC.free(targetptr)}
}
this.cachedResult = toString(unsafe { getresult(this.handle) })
if (code != 0) {
throw LuaError(unsafe { get_errno() }, this.cachedResult)
}
return this.cachedResult
}
/// 获取缓存的结果
public func result(): String { this.cachedResult }

View File

@ -1,4 +1,4 @@
package luarunner
package luaRunner
import std.unittest.* // cjlint-ignore G.PKG.01
import std.fs.* // cjlint-ignore G.PKG.01
@ -254,7 +254,58 @@ func testRedirectIoRead(): Unit {
}
// ====================
// 6. 错误码与回调
// 6. doString 测试
// ====================
@Test
func testDoStringSimple(): Unit {
let runner = LuaRunner()
let res = runner.doString("return 1 + 1")
@Expect(res, "2")
}
@Test
func testDoStringWithGlobal(): Unit {
let runner = LuaRunner()
let res = runner.doString("g = 42; return g")
@Expect(res, "42")
}
@Test
func testDoStringNoReturn(): Unit {
let runner = LuaRunner()
try {
runner.doString("x = 10")
fail("Should throw bad ret error")
} catch (e: LuaError) {
@Expect(e.code, 5011)
}
}
@Test
func testDoStringSyntaxError(): Unit {
let runner = LuaRunner()
try {
runner.doString("if true then")
fail("Should throw syntax error")
} catch (e: LuaError) {
@Expect(e.code, 5020)
}
}
@Test
func testDoStringNilReturn(): Unit {
let runner = LuaRunner()
try {
runner.doString("return nil")
fail("Should throw bad ret error")
} catch (e: LuaError) {
@Expect(e.code, 5011)
}
}
// ====================
// 7. 错误码与回调
// ====================
@Test