Skip to content

Commit 9168ead

Browse files
authored
Merge pull request #9 from kiss-lang/configure-throw
allow configuring behavior on unsupported conversion
2 parents ecb676e + 1a7ea01 commit 9168ead

File tree

1 file changed

+37
-7
lines changed

1 file changed

+37
-7
lines changed

src/vm/lua/Lua.hx

Lines changed: 37 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ import vm.lua.Thread;
1616
import vm.lua.Macro.*;
1717
import haxe.DynamicAccess;
1818

19+
enum BadConversionBehavior {
20+
Silent;
21+
Warn;
22+
Throw;
23+
}
24+
1925
#if cpp
2026
@:headerCode('#include "linc_lua.h"')
2127
#end
@@ -125,20 +131,44 @@ class Lua {
125131
toLuaValue(l, obj.get(key), cast obj);
126132
lua_settable(l, -3);
127133
}
128-
case TClass(Lua):
129-
lua_pushnil(l);
130134
case TClass(_):
131135
lua_newtable(l);
132136
for(key in Type.getInstanceFields(Type.getClass(v))) {
133137
lua_pushstring(l, key);
134138
toLuaValue(l, Reflect.getProperty(v, key), v);
135139
lua_settable(l, -3);
136140
}
137-
case t: throw 'Cannot convert $t to Lua value';
141+
case t: pushNilOrThrow(l, 'Cannot convert $t to Lua value');
138142
}
139143
return 1;
140144
}
141145

146+
public static var badConversionBehavior(default, default):BadConversionBehavior = Warn;
147+
148+
static function returnNullOrThrow(message:String) {
149+
switch (badConversionBehavior) {
150+
case Silent:
151+
return null;
152+
case Warn:
153+
trace('Warning: $message');
154+
return null;
155+
case Throw:
156+
throw message;
157+
}
158+
}
159+
160+
static function pushNilOrThrow(l, message:String) {
161+
switch (badConversionBehavior) {
162+
case Silent:
163+
lua_pushnil(l);
164+
case Warn:
165+
trace('Warning: $message');
166+
lua_pushnil(l);
167+
case Throw:
168+
throw message;
169+
}
170+
}
171+
142172
static function toHaxeValue(l, i:Int):Any {
143173
return switch lua_type(l, i) {
144174
case t if (t == TNIL): null;
@@ -156,12 +186,12 @@ class Lua {
156186
for(arg in args) toLuaValue(l, arg);
157187
if(lua_pcall(l, args.length, 1, 0) == OK) return getReturnValues(l) else throw getErrorMessage(l);
158188
});
159-
case f: throw 'Cannot convert CFUNCTION to Haxe value';
189+
case f: returnNullOrThrow('Cannot convert CFUNCTION to Haxe value');
160190
}
161191
case t if (t == TTHREAD): new Thread(lua_tothread(l, i));
162-
case t if (t == TUSERDATA): throw 'Cannot convert TUSERDATA to Haxe value';
163-
case t if (t == TLIGHTUSERDATA): throw 'Cannot convert TLIGHTUSERDATA to Haxe value';
164-
case t: throw 'unreachable ($t)';
192+
case t if (t == TUSERDATA): returnNullOrThrow('Cannot convert TUSERDATA to Haxe value');
193+
case t if (t == TLIGHTUSERDATA): returnNullOrThrow('Cannot convert TLIGHTUSERDATA to Haxe value');
194+
case t: returnNullOrThrow('unreachable ($t)');
165195
}
166196
}
167197

0 commit comments

Comments
 (0)