How does one execute code from a variable?

Post Reply
User avatar
Alexander Divine
Posts: 65
Joined: Mon Dec 21, 2009 7:01 pm

How does one execute code from a variable?

Post by Alexander Divine »

I'm currently working on an animation engine of sorts. I have a series of timers all at different speeds. When enabled, they all do one thing only, which is to run a generic animation function.

What I'm hoping I can get the function to do is basically look through a list of other functions that define how to properly animate a health bar, or how to animate a small, custom-made sprite on the screen. The point is that this must be entirely variable depending on the current situation.

What I'm looking for now is a way to tell Lua to basically, uh... do code. In zMud it was a lot easier -- you could put a line of script in @foo, and then a simple #EXECUTE {@foo} would make it interpret literally whatever was in @foo. You could of course have a script alter @foo at any given moment, which obviously makes the #EXECUTE script behave differently depending on what was in there.

Is this possible? Or can you possibly think of a better approach to my idea? Any advice is much appreciated.

User avatar
Heiko
Site Admin
Posts: 1548
Joined: Wed Mar 11, 2009 6:26 pm

Re: How does one execute code from a variable?

Post by Heiko »

Of course it's possible. Lua has real closure support and Lua can compile & run Lua code on the fly. Checkout the appropriate sections in the Lua programming online book quoted in the sticky Lua topic.

User avatar
Vadi
Posts: 5042
Joined: Sat Mar 14, 2009 3:13 pm

Re: How does one execute code from a variable?

Post by Vadi »

"execute code from a variable?" -> lua functions are variables. So, you can execute a variable... well, just the same way you can execute a function!
Code: [show] | [select all] lua
test = {}
test.a = function()
    print "hey!"
  end

test.a()

---

function testme()
  print "hello!"
end

test = {a = testme}

test.a()

User avatar
Alexander Divine
Posts: 65
Joined: Mon Dec 21, 2009 7:01 pm

Re: How does one execute code from a variable?

Post by Alexander Divine »

Ohdeargoditworked. Yay! You guys rock, as always.

To any other nublet coming from zMud, here is what I determined.

Q: You can put a function in a variable. This is learned pretty early on. But now that the function is just sitting there, how do you make it... well, function?
A: Use parentheses.

Code: Select all

functionTable = {}
functionTable[1] = function()
  echo("\nThis")
end
functionTable[2] = function()
  echo("\nis")
end
functionTable[3] = function()
  echo("\na")
end
functionTable[4] = function()
  echo("\nfunction!")
end

-- Alias: ^test$ --

for i = 1,4 do
  functionTable[i]()
end

-- Output: --

This
is
a
function!

User avatar
Heiko
Site Admin
Posts: 1548
Joined: Wed Mar 11, 2009 6:26 pm

Re: How does one execute code from a variable?

Post by Heiko »

This is some code that tests dynamically created conditions for my test bot on the Lusternia test server.
If the bot gets into some unusual situation, auxiliary conditions are being posted as Lua code and removed from the respective condition tables if the problem is solved.

Code: Select all

function pushAuxCon( what )
	table.insert(m_aux_condition_table, what)
	return #m_aux_condition_table
end

function auxConditions()
	ret = true
	for k,v in ipairs( m_aux_condition_table ) do
		fg("green")
		echo("testing auxCondition#"..k..":"..v.."\n")
		local func = assert(loadstring(m_aux_condition_table[k]))
		if func() == false then
			echo("\ncondition not met:"..m_aux_condition_table[k].."\n")
			ret = false
		else	
			echo("\naux condition == false -> ready to move on\n")
		end
	end
	fg("red")
	echo("\naux conditions done: ret="..tostring(ret).."\n")
	resetFormat()
	return ret
end

User avatar
Alexander Divine
Posts: 65
Joined: Mon Dec 21, 2009 7:01 pm

Re: How does one execute code from a variable?

Post by Alexander Divine »

Okay, let's see if we can figure this one out.

I want to make an alias, sort of like in World of Warcraft, where if I type ^/run (.*)$ (ideally, /run and then some code), it'll execute it right there from the command line, for quick and dirty hacks, I guess, like being able to easily set a variable without having to modify my "test" alias to do it. Could someone give me an example of how this could work?


guy
Posts: 26
Joined: Wed Mar 03, 2010 5:41 am
Location: Seattle

Re: How does one execute code from a variable?

Post by guy »

Vadi beat me to the punch, so here is more explanation of what is going on.

I use ^!(.*) for my alias pattern because I tend to use this feature a lot and /run[space] is just too much typing =)
The lua code to run is

Code: Select all

assert(loadstring(matches[2]))()
It must be exactly that.
Also, it is handy to alias ^@(.*) to assert(loadstring("display(" .. matches[2] .. ")"))() for easy examination of variables.

assert(something) just returns something if something is non-nil. In this case, it checks that loadstring() worked correctly. loadstring(some_string) is a lua function that accepts lua code in some_string and then compiles it and returns it as a function (but doesn't execute what was written in some_string). So for instance

Code: Select all

f = loadstring([[echo("hi\n")]])
gets turned into the equivalent of if you had explicitly written

Code: Select all

f = function(...)
   echo("hi\n")
end
That's why the extra set of parenthesis are needed after assert() to get the result right away - loadstring returns a function. The reason for this is that you can pass in arguments to the function returned by loadstring. Here is a trivial example:

Code: Select all

code = [[local a,b = ... return a + b]]
f = assert(loadstring(code))
so that f(1,2) returns 3. Trickier things are possible:

Code: Select all

function genfunc(op)
   code = "return function(a,b) return a " .. op .. " b end"
   return assert(loadstring(code, op))()
end
plus = genfunc("+")
times = genfunc("*")
where plus(times(4,5),10) returns 30

As you can see, there are a lot of possibilities with loadstring for creating dynamic functions!

User avatar
Alexander Divine
Posts: 65
Joined: Mon Dec 21, 2009 7:01 pm

Re: How does one execute code from a variable?

Post by Alexander Divine »

Goddamn, that was a very helpful explanation.

Thank you guys for your patience dealing with me. I'm full of questions, but I always find that my biggest issue is that I'm not sure how to word them! I'm not hip to the lingo, if you will.

Mudlet wouldn't be nearly as good without its community.

Post Reply