This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
ViperLordX's profile picture

java.lang.ArrayIndexOutOfBoundsException at line 5?

Started by ViperLordX, 09 February 2016 - 09:33 PM
ViperLordX #1
Posted 09 February 2016 - 10:36 PM
So I've been trying to make a simple system to prevent people from defining global variables, and I did it like this:


args = {...}
if (#args == 1) then
  func = loadfile(args[1])
  env = {}
  setmetatable(env, {__index = _G, __newindex = function(table, val, var) env[var] = val end})
  setfenv(func, env)
  func()
end

However, when I run it on a simple program,


a = 1 print(a)

It tells me there's an ArrayIndexOutOfBoundsException at line 5 in gman, which is the one setting the metatable on env. Does anyone know why this is happening and how to fix it?

Ah, I found two problems after looking at my code for a while. I got two variables backwards, and I got a stack overflow by doing env[var] = val in the __newindex metamethod.
KingofGamesYami #2
Posted 09 February 2016 - 10:39 PM

__newindex = function( table, val, var ) env[ var ] = val end

Says to lua "When someone adds something to the env table, add something to the env table"

Which is an endless recursive function. Which crashes with that error.

To bypass __newindex, simply use rawset
Edited on 09 February 2016 - 09:39 PM
ViperLordX #3
Posted 09 February 2016 - 10:39 PM
Yes, thanks, but I already got it ;)/>