lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


вт, 30 июл. 2019 г. в 09:45, Abhijit Nandy <abhijit.nandy@gmail.com>:
>
> Hi,
>
> So we have quite a large Lua + Luabind code base and new comers from other languages often tend to forget the word local when declaring local variables in a block/scope. Of course the Lua static analyzer flags such code and we fix it, but sometimes such code still slips through basically because this particular warning is not an error at the moment.
>
> What I am wondering is, apart from using the static analyzer to catch it, is there any code patch that can make variable declarations local by default?
> Or is it too core to the language that changing this could cause issues elsewhere? I am willing to sacrifice performance as we are on PC and its worth doing this for us to prevent erroneous code if it can be done without requiring significant change to syntax.
>
> I had a look at http://lua-users.org/wiki/LocalByDefault but there does not yet seem to be any solutions for Lua 5.3 for doing this globally in the language.
>
I experimenting with "noupvalues" may be it could be useful
Here is bash script to build it
[build-lua-5.4-noupvalues.sh]
#/bin/sh
wget -c https://www.lua.org/work/lua-5.4.0-alpha.tar.gz
wget https://raw.githubusercontent.com/kov-serg/lua-aux/master/noupvalues54.patch
tar xf lua-5.4.0-alpha.tar.gz
cd lua-5.4.0-alpha
patch -p 1 < ../noupvalues54.patch
make linux-readline
cp src/{lua,luac} ..
cd ..

You can use it for local by default.
synatax https://www.lua.org/manual/5.3/manual.html#9
...
funcbody ::= ‘(’ [parlist] ‘)’ [noupvalues] block end
...


x=1 local y,z=2,3
function fn() noupvalues _ENV={ print=print }
  print(x,y,z) -- nil,nil,nil
  x,y,z=10,20,30
  print(x,y,z) -- 10,20,30 all unknown variables will be in local _ENV
  return _ENV
end
fn()
print(x,y,z) --1,2,3

or

function strict(s) s=s or {}
  return setmetatable({},{
    __index=function(t,n)
      if s[n]==nil then error("no "..n.." defined") end
      return s[n]
    end,
    __newindex=function(t,n,v)
      if s[n]==nil then error("no "..n.." defined") end
      s[n]=v
    end,
  })
end

local z=30
function fn(_ENV) noupvalues
  local x,y=10,20
  print(x,y,z) -- error: no z defined
end

fn(strict{ print=print })