Skip to content

Instantly share code, notes, and snippets.

@felipetavares
Created November 19, 2018 15:43
Show Gist options
  • Save felipetavares/6e9a637beae94fe58826b53f93d6ec26 to your computer and use it in GitHub Desktop.
Save felipetavares/6e9a637beae94fe58826b53f93d6ec26 to your computer and use it in GitHub Desktop.
+= extension for Lua 5.3
static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
expdesc e;
check_condition(ls, vkisvar(lh->v.k), "syntax error");
if (testnext(ls, ',')) { /* assignment -> ',' suffixedexp assignment */
struct LHS_assign nv;
nv.prev = lh;
suffixedexp(ls, &nv.v);
if (!vkisindexed(nv.v.k))
check_conflict(ls, lh, &nv.v);
checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS,
"C levels");
assignment(ls, &nv, nvars+1);
}
// Language extension begins here
// This is a extra token which matches '+='
else if (testnext(ls, TK_PLUSEQ)) {
// Get the expression
expr(ls, &e);
// Get the value
expdesc infix = lh->v;
// Sum
luaK_infix(ls->fs, OPR_ADD, &infix);
luaK_posfix(ls->fs, OPR_ADD, &infix, &e, ls->linenumber);
// Store the result in the variable itself
luaK_storevar(ls->fs, &lh->v, &infix);
return; /* avoid default */
}
...
@felipetavares
Copy link
Author

This works for the simple case x += 1 and x.y += 1 but not for:

local x = {
  x = {
    x = 0
  }
}

x.x.x += 1

which fails with: attempt to index a number value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment