Space Lua: Align .. (concatenation) operator (#1648)
* Make fallback accept only strings and numbers (as per standard Lua). * Remove `luaToString` from the fallback. It fits well presentation purposes but is too complicated for strict semantic checking in the evaluator and also wrongly coersed non-string and non-number value. It may also return a promise but we require synchronous error path. * Concatenating `nil` now throws "attempt to concatenate nil value" as per standard Lua. * Other types throw "attempt to concatenate a non-string or non-number" which is simplified message diverting from standard Lua which throws typed error but we do not strictly need that for Space Lua (and can be easily added anytime in the future). Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>
This commit is contained in:
+21
-10
@@ -25,7 +25,6 @@ import {
|
||||
luaSet,
|
||||
type LuaStackFrame,
|
||||
LuaTable,
|
||||
luaToString,
|
||||
luaTruthy,
|
||||
type LuaType,
|
||||
luaTypeOf,
|
||||
@@ -834,15 +833,27 @@ const operatorsMetaMethods: Record<string, {
|
||||
},
|
||||
"..": {
|
||||
metaMethod: "__concat",
|
||||
nativeImplementation: (a, b) => {
|
||||
const aString = luaToString(a);
|
||||
const bString = luaToString(b);
|
||||
|
||||
if (aString instanceof Promise || bString instanceof Promise) {
|
||||
return Promise.all([aString, bString]).then(([a, b]) => a + b);
|
||||
} else {
|
||||
return aString + bString;
|
||||
}
|
||||
nativeImplementation: (a, b, ctx, sf) => {
|
||||
// Accepts only strings or numbers (coerced to strings)
|
||||
const coerce = (v: any): string => {
|
||||
if (v === null || v === undefined) {
|
||||
throw new LuaRuntimeError(
|
||||
"attempt to concatenate a nil value",
|
||||
sf.withCtx(ctx),
|
||||
);
|
||||
}
|
||||
if (typeof v === "string") {
|
||||
return v as string;
|
||||
}
|
||||
if (typeof v === "number" || v instanceof Number) {
|
||||
return String(v instanceof Number ? Number(v) : v);
|
||||
}
|
||||
throw new LuaRuntimeError(
|
||||
"attempt to concatenate a non-string or non-number",
|
||||
sf.withCtx(ctx),
|
||||
);
|
||||
};
|
||||
return coerce(a) + coerce(b);
|
||||
},
|
||||
},
|
||||
"==": {
|
||||
|
||||
Reference in New Issue
Block a user