Introspection with Lua

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Introspection with Lua

Vinj Vinj
I'm migrating some programs from python to lua and had some questions about introspection in Lua. Specifically I'm looking for the equivalent of python's setattr and getattr in Lua.

I need to find out (dynamically) if a certain lua module has some functions and variables defined. I also need to set some module variables (dynamically).


Reply | Threaded
Open this post in threaded view
|

Re: Introspection with Lua

Romulo Bahiense
Vineet Jain wrote:
I need to find out (dynamically) if a certain lua module has some functions and variables defined. I also need to set some module variables (dynamically).

If your module follows 5.1 package system...


local mod = require 'mymodule'

if mod.somefunction~=nil then
    print("Module has somefunction")
end

if mod.someattr == "MagicKey" then
    print("Module has the secret. Don't tell anyone")
    mod.GotThePower = true
end



By "if your module follows 5.1 package system" I mean:

-- mymodule.lua

module("mymodule")

someattr = "MagicKey"

function somefunction(...)
end

function conspiracy()
    if (GotThePower) then
        print ":D"
    end
end

-- end of mymodule.lua


A module is, usually, a table with functions and other values inside it. That Simple(tm).

Good luck,
me.

Reply | Threaded
Open this post in threaded view
|

Re: Introspection with Lua

Vinj Vinj
In reply to this post by Vinj Vinj

I need to find out (dynamically) if a certain lua module has some functions and variables defined. I also need to set some module variables (dynamically).
After some googling I came across _G, is this how you can check if a function/variable exists in a lua module? Can you also use this to dynamically assign variables to lua modules?

Vineet



Reply | Threaded
Open this post in threaded view
|

Re: Introspection with Lua

Petite Abeille

On May 16, 2006, at 04:49, Vineet Jain wrote:


I need to find out (dynamically) if a certain lua module has some functions and variables defined. I also need to set some module variables (dynamically).
After some googling I came across _G, is this how you can check if a function/variable exists in a lua module? Can you also use this to dynamically assign variables to lua modules?

_G is the current environment.

And as mentioned by Romulo, a module is a table. Lookup the key you are after to check for membership:

local math = require( "math" )

if type( math.abs ) ~= "function" then
    math.abs = function() end
end

if math.PI == nil then
    math.PI = 3.14159265
end

Cheers

--
PA, Onnay Equitursay
http://alt.textdrive.com/