diff options
-rw-r--r-- | README.md | 2 | ||||
-rw-r--r-- | src/lauxlib.js | 4 | ||||
-rw-r--r-- | src/lbaselib.js | 13 | ||||
-rw-r--r-- | tests/lbaselib.js | 29 |
4 files changed, 44 insertions, 4 deletions
@@ -215,7 +215,7 @@ - [x] ipairs - [x] select - [x] tonumber - - [ ] assert + - [x] assert - [ ] next - [ ] pairs - [ ] rawlen diff --git a/src/lauxlib.js b/src/lauxlib.js index c44780e..e295fe6 100644 --- a/src/lauxlib.js +++ b/src/lauxlib.js @@ -12,9 +12,7 @@ const CT = lua.constant_types; const LUA_LOADED_TABLE = "_LOADED" const panic = function(L) { - let msg = `PANIC: unprotected error in call to Lua API (${lapi.lua_tostring(L, -1)})`; - console.error(msg); - return 0; + throw new Error(`PANIC: unprotected error in call to Lua API (${lapi.lua_tostring(L, -1)})`); }; // const luaL_argerror = function(L, arg, extramsg) { diff --git a/src/lbaselib.js b/src/lbaselib.js index 9cc4fb1..fa0349b 100644 --- a/src/lbaselib.js +++ b/src/lbaselib.js @@ -165,6 +165,18 @@ const luaB_error = function(L) { return lapi.lua_error(L); }; +const luaB_assert = function(L) { + if (lapi.lua_toboolean(L, 1)) /* condition is true? */ + return lapi.lua_gettop(L); /* return all arguments */ + else { + lauxlib.luaL_checkany(L, 1); /* there must be a condition */ + lapi.lua_remove(L, 1); /* remove it */ + lapi.lua_pushliteral(L, "assertion failed!"); /* default message */ + lapi.lua_settop(L, 1); /* leave only message (default if no other one) */ + return luaB_error(L); /* call 'error' */ + } +}; + const luaB_select = function(L) { let n = lapi.lua_gettop(L); if (lapi.lua_type(L, 1) === CT.LUA_TSTRING && lapi.lua_tostring(L, 1) === "#") { @@ -220,6 +232,7 @@ const luaB_xpcall = function(L) { const base_funcs = { "collectgarbage": function () {}, + "assert": luaB_assert, "print": luaB_print, "tostring": luaB_tostring, "tonumber": luaB_tonumber, diff --git a/tests/lbaselib.js b/tests/lbaselib.js index 6dc6bfb..a7b14d9 100644 --- a/tests/lbaselib.js +++ b/tests/lbaselib.js @@ -489,4 +489,33 @@ test('tonumber', function (t) { 2, "Correct element(s) on the stack" ); +}); + + +test('assert', function (t) { + let luaCode = ` + assert(1 < 0, "this doesn't makes sense") + `, L; + + t.plan(2); + + t.doesNotThrow(function () { + + let bc = toByteCode(luaCode).dataView; + + L = lauxlib.luaL_newstate(); + + linit.luaL_openlibs(L); + + lapi.lua_load(L, bc, "test-assert"); + + lapi.lua_pcall(L, 0, -1, 0); + + }, "JS Lua program ran without error"); + + t.ok( + lapi.lua_tostring(L, -1).endsWith("this doesn't makes sense"), + "Error is on the stack" + ); + });
\ No newline at end of file |