Jump to content




java.lang.ArrayIndexOutOfBoundsException at line 5?

help lua

  • You cannot reply to this topic
2 replies to this topic

#1 ViperLordX

  • Members
  • 43 posts
  • LocationEarth

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.

#2 KingofGamesYami

  • Members
  • 3,002 posts
  • LocationUnited States of America

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 by KingofGamesYami, 09 February 2016 - 10:39 PM.


#3 ViperLordX

  • Members
  • 43 posts
  • LocationEarth

Posted 09 February 2016 - 10:39 PM

Yes, thanks, but I already got it ;)





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users