Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add compiler warning/error for duplicate variable declaration in Lua 5.2.4
--- lparser.c
+++ lparser.c
@@ -6,6 +6,7 @@
#include <string.h>
+#include <stdio.h>
#define lparser_c
#define LUA_CORE
@@ -67,6 +68,15 @@
}
+static void parser_warning (LexState *ls, const char *msg) {
+ char buff[LUA_IDSIZE];
+ luaO_chunkid(buff, getstr(ls->source), LUA_IDSIZE);
+ msg = luaO_pushfstring(ls->L, "%s:%d: warning %s", buff, ls->linenumber, msg);
+ fprintf(stderr, "%s\n", msg);
+ fflush(stderr);
+}
+
+
/* semantic error */
static l_noret semerror (LexState *ls, const char *msg) {
ls->t.token = 0; /* remove 'near to' from final message */
@@ -178,6 +188,29 @@
static void new_localvar (LexState *ls, TString *name) {
FuncState *fs = ls->fs;
Dyndata *dyd = ls->dyd;
+ /* allow '_' and '(for...' duplicates */
+ const char *str_name = getstr(name);
+ if(!(str_name[0] == '(' || (name->tsv.len == 1 && str_name[0] == '_'))) {
+ int vidx, nactvar_n, first_block_local;
+ vidx = fs->firstlocal;
+ nactvar_n = dyd->actvar.n;
+ first_block_local = fs->bl ? fs->bl->nactvar+fs->firstlocal : 0;
+ for (; vidx < nactvar_n; ++vidx) {
+ LocVar *lv = &fs->f->locvars[dyd->actvar.arr[vidx].idx];
+ if (lv && name == lv->varname) {
+ if(vidx < first_block_local) {
+ int saved_top = lua_gettop(ls->L);
+ parser_warning(ls, luaO_pushfstring(ls->L,
+ "Name [%s] already declared will be shadowed", str_name));
+ lua_settop(ls->L, saved_top);
+ }
+ else {
+ luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
+ "Name [%s] already declared", str_name));
+ }
+ }
+ }
+ }
int reg = registerlocalvar(ls, name);
checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
MAXVARS, "local variables");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.