Post your best Lua script examples here

User avatar
By zivimo
#45739 Hey,

I'm trying to get this to work but it doesnt seem to. Have a look at the following:

test_func.lua
Code: Select alllocal test = {MOD_NAME = "test"}

function test:init()
    print(node.heap())
    self.text = "sdfjga.....kafndjk"   # long string
    print(node.heap())
end

function test:tprint()
    print(node.heap())
    print(self.text)
    print(node.heap())
end

flashMod(test)


And the following file:

use_flash_funcs.lua
Code: Select alllocal test = flashMod("test")
test:init()
test:tprint()


After loading both to the ESP I do as follows:

Code: Select all> =node.heap()
40032
> dofile("test_func.lua")
> =node.heap()
39984
> dofile("test_func2.lua")
35504   # heap before init
35480   # heap after init
35024
sdfjga.....kafndjk   # that long string
35440
>


The string is a litte less than 3k long and this seem to correspond to the heap usage of dofile("test_func2.lua"). Did that all work as exspected? To me it doesnt seem to. I'm really sorry if I missed something but what have I done wrong?

Thank you for your help!
User avatar
By dpwhittaker
#46265 Man, it's been a while since I looked at this, but I think I can help you out.

flash functions is just that - it stores the function itself in flash. self.text, however, is data - so by loading the function into memory, you pull the constant string out of flash, but when you assign it to self.text, you assign that reference to something the garbage collector can reach, so it stays in memory forever (or at least until that local test goes out of scope). So, there are two tricks you can use for data - write that data to a file, and read the file into a local variable whenever you need to use it (see the font files in the oledv2 example at the top), or use the constant string directly wherever you need it. Here's an application of the second that makes it relatively straightforward - I'm borrowing the concept of properties from languages like C# to turn that data into a function:

Code: Select alllocal test = {MOD_NAME = "test"}

function test:text()
    print(node.heap()) #heap usage should jump up
    return "sdfjga.....kafndjk"   # long string
end

function test:tprint()
    print(node.heap()) #heap usage should still be low
    print(self.text())  #notice the () function call
    #collectgarbage() -- may need to collect here to see the heap space returned.
    print(node.heap())
end

flashMod(test)


Now, that text is safely tucked away in a function that is written to flash. You'll probably still see the heap size high while the function is running, because the garbage collector never got a chance to run after that return value was no longer needed, but you could put a collectgarbage() call just before that last print to see it in action - or just call node.heap() from the command line after you execute it to see you get your heap back.