Dynamic Function Calls

Discuss using and improving Lua and the Lua Player specific to the PSP.

Moderators: Shine, Insert_witty_name

Post Reply
JC
Posts: 16
Joined: Fri Jun 02, 2006 9:30 am

Dynamic Function Calls

Post by JC »

Hi Folks,

I not sure if what I am trying to do is possible, hopefully someone will be able to shed some light. I want to pass a function name to a second function and get the second function to call the first one.

eg:

Code: Select all

Main(SubMain,"blah")


function Main(pName,pstuff)

execute function (pName)

stuff........

end 


function SubMain()

stuff here........

end 
Can it be done ?

TIA,
JC
Remember, don't sweat the petty things
and don't pet the sweaty things.......
romero126
Posts: 200
Joined: Sat Dec 24, 2005 2:42 pm

Post by romero126 »

Yes

Code: Select all

Variables are handled as functions.
So any variable can be passed off as a function
If it doesnt error out that is.




function Main(pName, pStuff)
	if (type(pName) == "function") then
		result = pName() -- result is whatever pName returns
	else
		-- Not a function!@#?!
	end
	
	print(result)

end

function MySub()
	-- blah blah blah
	return "value" -- returns back to main.
end
For more information http://www.lua.org/manual/5.0/manual.html#2.5.8
User avatar
daurnimator
Posts: 38
Joined: Sun Dec 11, 2005 8:36 pm
Location: melbourne, australia

Post by daurnimator »

why wouldn't you?

try: (code works)

Code: Select all


function SubMain()
        screen:print(0,0,"test",Color.new(255,0,0))
end
function Main(func)
        while true do
                screen:clear(Color.new(255,255,255))
                func()
                screen.flip()
        end
end

Main(SubMain)


User avatar
daurnimator
Posts: 38
Joined: Sun Dec 11, 2005 8:36 pm
Location: melbourne, australia

Post by daurnimator »

damn, beat me ;)
JC
Posts: 16
Joined: Fri Jun 02, 2006 9:30 am

Post by JC »

Wonderful. Thanks for the help (and the quick replies).

JC
Remember, don't sweat the petty things
and don't pet the sweaty things.......
romero126
Posts: 200
Joined: Sat Dec 24, 2005 2:42 pm

Post by romero126 »

daurnimator wrote:why wouldn't you?

try: (code works)

Code: Select all


function SubMain()
        screen:print(0,0,"test",Color.new(255,0,0))
end
function Main(func)
        while true do
                screen:clear(Color.new(255,255,255))
                func()
                screen.flip()
        end
end

Main(SubMain)



No error-checking.
No way to terminate loop.
screen:clear() doesnt need to be called.
screen.flip() -- might not be needed.
Too much extra code and not enough explination.
Sorry I dont mean to nitpick at your code, but I thought it might help!
Post Reply