Vladimir
Vladimir

Reputation: 1622

How to redefine a LUA function globally

I have redefined a Print function in Lua

local myThing = PrintThing
function PrintThing (text)

    ... some code ...

    return myThing(text)

end

It works for my local script

But not in other scripts

How to redefine this print function globally?

Upvotes: 3

Views: 2566

Answers (3)

The19thFighter
The19thFighter

Reputation: 101

Your software probably creates a new state for every scripting file it loads, to avoid conflict between different "plugins".

Means overloading it globally is impossible, unless you're going to modify the programm (and you probably won't have access to the source, if it's a hacking/scripting framework, plus it's probably obfuscated).

However what you can normally do is, creating a file, which overloads that function and including it into the beginning of every file, which creates a new state.

Also: Many of those plugin based frameworks have the ability to load a global lua file, in this case you'd need to find out if something like this exists for yours.

For what I can tell, creating a file inside the libs folder, which overrides that function should work for you.

If you're using, what I think you're using.

Upvotes: 0

moteus
moteus

Reputation: 2235

In general you cant. In best you can just redefine function in global environment (_G.PrintThing=...). But even this is not always allows. E.g. host app run your code in sandbox and do not provide access to global env. In such case you have to make C module to get access to global env (but I do not think that sandboxed env allows load such module). Second varian is - set this function in your environment. And if you load new modules in same envirionment then you just need redefine function before you load your library. If you try redefine function after you load module it will be depend on module itself. e.g. if use local PrintThing = PrintThing it will not see your new function after load. Also C code may use C functions directly.

Upvotes: 4

Mud
Mud

Reputation: 28991

How to redefine this print function globally?

Modify the Lua source and built your own interpreter.

print is defined in the Lua source. The only way to redefine it as runtime is to run code similar to what you've shown.

Upvotes: 0

Related Questions