Search code examples
multithreadinglualove2d

Love2D, Threads execution and input


Please, i got a problem with Love2d thread functions, and i didnt find any examples or explanations i would understand anywhere.

first: in main file i got:

thread1 = love.thread.newThread("ambient.lua")
thread2 = love.thread.newThread("ambient.lua")
thread1:start()
thread2:start()

ambient.lua contains:

random1 = love.math.random(1, 10)
gen1 = love.audio.newSource("audio/ambient/gen/a/gen_a_".."random1"..".mp3", 
"static")
gen1:setVolume(1.0)
gen1:setLooping(false)
gen1:play()

works fine, problem is that when i ask var = Thread1:isRunning( ) in same step or with delay, when audio is playing and try to print it, it throws error (is supposedly null). when the audio finishes, i see that memory is cleared. also if i link thread1:start() to mouse click and then start it multiple times in short time, memory usage goes up like crazy, then after time similar to sample length it starts to decrease. question is, am i creating multiple threads? in that case did they even terminate properly after samples ended? or is the thread lifetime just 1-step long and i am only creating multiple audio sources playing with the same thread? is problem in the check itself?

next issue is that i need to use thread1:start() with values:

thread1:start(volume, sampleID)

and i have no clue how to addres them in the thread itself. guides and examples says "vararg" reference. i didnt see any decent explanation or any example containing "..." usage in variable input into threads. i am in need of example how to write it. even if this audio fiddle is not a great example, i will surely need it for AI. No need for complicated input, just simple x,y,size,target_x,target_y values.


Solution

  • and i have no clue how to addres them in the thread itself. guides and examples says "vararg" reference. i didnt see any decent explanation or any example containing "..." usage in variable input into threads

    You didn't read manuals enough. Every loaded Lua chunk (section 2.4.1 of Lua 5.1 manuals) is an anonymous function with variable number of arguments.
    When you call love.thread.newThread("ambient.lua"), Love2D will create new chunk, so basic Lua rules applies to this case.
    In your example, volume and sampleID parameters from within thread would be retrieved like this:

    local volume, sampleID = ...
    
    gen1 = love.audio.newSource(get_stream_by_id(sampleID), "static")
    gen1:setVolume(volume)
    gen1:setLooping(false)
    gen1:play()