Author Topic: Choosing a Function Randomly  (Read 144 times)

Bagu

  • Newbie
  • *
  • Posts: 26
    • View Profile
Choosing a Function Randomly
« on: June 09, 2018, 03:03:23 am »
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
  1. choices = {"enemy:go_hero()","enemy:random_pause()","enemy:jump_pause()","enemy:go_random()"}
  2.  
  3.   sol.timer.start(enemy, math.random(1, 3000), function()
  4.     choices[math.random( 1, #choices )]
  5. end)
  6.  

Code: Lua
  1. function enemy:pickaction()
  2. math.randomseed(os.time())
  3. local a = {"go_hero","random_pause","jump_pause","go_random"}
  4. a[math.random(1,#a)]
  5. end
  6.  
  7.   sol.timer.start(enemy, math.random(1, 3000), function()
  8.     enemy:pickaction()
  9.   end)
  10.  

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?

llamazing

  • Full Member
  • ***
  • Posts: 118
    • View Profile
Re: Choosing a Function Randomly
« Reply #1 on: June 09, 2018, 06:36:51 am »
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
  1. choices = {"go_hero","random_pause","jump_pause","go_random"}
  2.  
  3.   sol.timer.start(enemy, math.random(1, 3000), function()
  4.     enemy[ choices[math.random( 1, #choices )] ](enemy)
  5.     --NOTE: enemy:go_hero() is equivalent to enemy.go_hero(enemy) which is equivalent to enemy["go_hero"](enemy)
  6. end)

Bagu

  • Newbie
  • *
  • Posts: 26
    • View Profile
Re: Choosing a Function Randomly
« Reply #2 on: June 09, 2018, 07:35:07 pm »
llamazing, you're right - that's exactly what I needed and it works perfectly. Thanks!!!