Skip to content

Commit ab889f0

Browse files
committed
Add safety to toNumber and toInteger in Lua 5.1
This makes the behavior of toNumber and toInteger in Lua 5.1 match that of all other target Lua versions in Ziglua. That is, if the conversion fails it will return a Zig error rather than returning a 0. Although this does add an additional internal function call and condition, this added safety is worth it.
1 parent 25ebb59 commit ab889f0

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

src/lib.zig

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1911,7 +1911,9 @@ pub const Lua = opaque {
19111911
pub fn toInteger(lua: *Lua, index: i32) !Integer {
19121912
switch (lang) {
19131913
.lua51 => {
1914-
return c.lua_tointeger(@ptrCast(lua), index);
1914+
const result = c.lua_tointeger(@ptrCast(lua), index);
1915+
if (result == 0 and !lua.isNumber(index)) return error.Fail;
1916+
return result;
19151917
},
19161918
else => {
19171919
var success: c_int = undefined;
@@ -1929,7 +1931,9 @@ pub const Lua = opaque {
19291931
pub fn toNumber(lua: *Lua, index: i32) !Number {
19301932
switch (lang) {
19311933
.lua51 => {
1932-
return c.lua_tonumber(@ptrCast(lua), index);
1934+
const result = c.lua_tonumber(@ptrCast(lua), index);
1935+
if (result == 0 and !lua.isNumber(index)) return error.Fail;
1936+
return result;
19331937
},
19341938
else => {
19351939
var success: c_int = undefined;

src/tests.zig

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,25 @@ test "standard library loading" {
153153
}
154154
}
155155

156+
test "number conversion success and failure" {
157+
const lua = try Lua.init(&testing.allocator);
158+
defer lua.deinit();
159+
160+
_ = lua.pushString("1234.5678");
161+
try expectEqual(1234.5678, try lua.toNumber(-1));
162+
163+
_ = lua.pushString("1234");
164+
try expectEqual(1234, try lua.toInteger(-1));
165+
166+
lua.pushNil();
167+
try expectError(error.Fail, lua.toNumber(-1));
168+
try expectError(error.Fail, lua.toInteger(-1));
169+
170+
_ = lua.pushString("fail");
171+
try expectError(error.Fail, lua.toNumber(-1));
172+
try expectError(error.Fail, lua.toInteger(-1));
173+
}
174+
156175
test "arithmetic (lua_arith)" {
157176
if (!langIn(.{ .lua52, .lua53, .lua54 })) return;
158177

0 commit comments

Comments
 (0)