Hack Forums
[Lua] overrided print function - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Coders Lounge (https://hackforums.net/forumdisplay.php?fid=5)
+---- Thread: [Lua] overrided print function (/showthread.php?tid=4432549)



overrided print function - Remix - Sep 5, 2014

Hey everybody

i'm very bored so i tried to find something useful for LUA and i was thinking about the print and string.format function. I ever hated it to use the string.format function because i'm fking lazy.
So i had the idea to override the basic print function that you can use multiple arguments that you normaly just could use with the string.format function.

Example:

Code
print("hello %s", "hackforums")

The function:

Code
main_print = main_print or print

function print(text, ...)
    if text == nil then return end
    if table.getn(arg) < 1 then
        return main_print(text)
    end
    main_print(string.format(text, unpack(arg)))
end

It's nothing special but it should help those people who are as lazy as i am.

Sincerely
[iRemix]


* - haffy - Sep 6, 2014

I don't see how it would be useful to overwrite the print function with this, also, this is not how you detour properly.

You would have to do:

main_print = main_print or print
or
local main_print = print

If you assign the global "main_print" to print then detour print, the next time that your code runs it will assign the detoured print to main_print and detour it again, this will cause a stack overflow.


* - Remix - Sep 6, 2014

(Sep 6, 2014 12:43 PM)Hafnium Wrote:  I don't see how it would be useful to overwrite the print function with this, also, this is not how you detour properly.

You would have to do:

main_print = main_print or print
or
local main_print = print

If you assign the global "main_print" to print then detour print, the next time that your code runs it will assign the detoured print to main_print and detour it again, this will cause a stack overflow.

If it will be used in a lua script which will be loaded again and again you're right. I didn't think about that.
I used that script in a lib which is just loaded once.
I've corrected it right now, thank you.


* - haffy - Sep 6, 2014

(Sep 6, 2014 03:04 PM)[iRemix] Wrote:  If it will be used in a lua script which will be loaded again and again you're right. I didn't think about that.
I used that script in a lib which is just loaded once.
I've corrected it right now, thank you.

No problem, if you want to just save the trouble of having to check if main_print exists, just make it a local, I can't think of a reason for it to be global anyways 🤝