Changes to the Lua initialization in MUSHclient v4.60

Posted by Nick Gammon on Sun 05 Sep 2010 02:44 AM — 3 posts, 9,014 views.

Australia Forum Administrator #0
As part of code cleanups for version 4.60 of MUSHclient, I noticed that the implementation of the main script spaces metatables was wrong (it is confusing reading the C code to set it up).

To demonstrate, in any version below 4.60 you can try this:


print (_G)        --> table: 00D0B6B8
print (world)     --> table: 00CE6A38
print (rawget (_G, "__index"))  --> nil
print (rawget (world, "__index")) --> table: 00CE6A38
print (getmetatable (_G))         --> table: 00CE6A38
print (getmetatable (world))      --> nil
world.__index = nil
Note "hello"  --> Error: attempt to call global 'Note' (a nil value)


You can see that the above is wrong in a number of ways. It is as if this was coded in Lua:


setmetatable (_G, world)
world.__index = world


It should in fact look more like this:


setmetatable (_G, { __index = world } )


Also, setting world.__index to nil should not stop access to the world functions from the global environment.

In version 4.60 the results are like this:


print (_G)      --> table: 020547A0
print (world)   --> table: 0205ED30
print (rawget (_G, "__index"))    --> nil
print (rawget (world, "__index")) --> nil
print (getmetatable (_G))     --> table: 0205EC90
print (getmetatable (world))  --> nil
world.__index = nil 
Note "hello"   --> hello


Now there is no "__index" field in the world table, and the global environment has a metatable which is different from the world table. This metatable simply indexes back to the world table. If you set world.__index it has no effect (it was nil anyway).

Now these changes *shouldn't* affect existing scripts, but I mention them in case anyone has done some obscure mucking around with metatables and are relying on the current behaviour.
Amended on Sun 05 Sep 2010 02:45 AM by Nick Gammon
USA #1
Fun side effect of the pre-4.60 behavior: you can access the world table as __index, too.

__index.Note("lolwat")
Australia Forum Administrator #2
Yeah, exactly why it was wrong. ;)

Well spotted.