lua - Setting __index of current environment in Roblox -


in roblox studio, have modulescript object implements analogous class 1 shown in chapter 16 of 1st edition of programming in lua, shown below:

local h4x0r = { }  local function setcurrentenvironment( t, env )     if ( not getmetatable( t ) )          setmetatable( t, { __index = getfenv( 0 ) } )     end      setfenv( 0, t ) end      setcurrentenvironment( h4x0r );              h4x0r.account = { };         setcurrentenvironment( h4x0r.account );         __index = h4x0r.account;          function withdraw( self, v )             self.balance = self.balance - v;             return self.balance;         end          function deposit( self, v )             self.balance = self.balance + v;             return self.balance;         end          function new( )             return setmetatable( { balance = 0 }, h4x0r.account )         end          setcurrentenvironment( h4x0r );     end end  return h4x0r 

i attempted use following script access account class, assuming of members of 2nd do-end block assigned h4x0r.account:

h4x0r = require( game.workspace.h4x0r ); account = h4x0r.account;  account = account.new( ); print( account:withdraw( 100 ) ); 

the above script fails error workspace.script:5: attempt call method 'withdraw' (a nil value), must issue regarding line set __index field of h4x0r.account.

can please explain me went wrong?

try using getfenv(2) , setfenv(2, t) instead of getfenv(0) , setfenv(0, t). want change environment of encapsulating function, stack level 2.

0 special argument instead or set environment of thread, used default environment in cases, not affect individual closures have been instantiated in thread, hence doesn't work in case.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -