Choosing a Function Randomly

Started by Bagu, June 09, 2018, 03:03:23 AM

Previous topic - Next topic
I've looked at a few different methods of making a random selection from a table, as a means to make an enemy AI choose a function as its next action. For example:

Code ( lua) Select
choices = {"enemy:go_hero()","enemy:random_pause()","enemy:jump_pause()","enemy:go_random()"}

  sol.timer.start(enemy, math.random(1, 3000), function()
    choices[math.random( 1, #choices )]
end)


Code ( lua) Select
function enemy:pickaction()
math.randomseed(os.time())
local a = {"go_hero","random_pause","jump_pause","go_random"}
a[math.random(1,#a)]
end

  sol.timer.start(enemy, math.random(1, 3000), function()
    enemy:pickaction()
  end)


I've tried about 20 different variations of this approach and always wind up with an error message like "= expected near end" or "function arguments expected near [".

I can get it to print the desired results to the console but the engine doesn't seem to want to accept them as anything remotely resembling a function. What am I doing wrong?

There are a number of problems with what you posted.

For starters, the functions you are listing in the choices table are strings, so you won't be able to execute them like functions.

And secondly, line 4 of the first one just gets the contents of the table, you still have to do something with it.

Try this:
Code (lua) Select

choices = {"go_hero","random_pause","jump_pause","go_random"}

  sol.timer.start(enemy, math.random(1, 3000), function()
    enemy[ choices[math.random( 1, #choices )] ](enemy)
    --NOTE: enemy:go_hero() is equivalent to enemy.go_hero(enemy) which is equivalent to enemy["go_hero"](enemy)
end)

llamazing, you're right - that's exactly what I needed and it works perfectly. Thanks!!!