Game NPC multi-action lua script design

1k views Asked by At

I need to put scriptable NPC in my currect game project. The project itself is developed in C++ language. I will using Luabind to bind lua and c++.

I need to call NPC function when certain NPC clicked or timer to do something is activated. Currently I stuck between 2 NPC script design.

  1. Using a kind of npcname_action to differentiate every NPC.
    This is kind of troublesome to give name to every different NPC.
    I'm still thinking how to implement this in my project.
    Example:

    HotelBellboy12_Click() { .. }  
    HotelBellboy12_TimerAction() { .. }
    
  2. Using name of function.
    Every npc have it own lua file.
    I'm thinking to load script into memory and when needed will be loaded into luaState using luaL_loadbuffer
    Example:

    OnClick() { .. }
    OnTimerAction() { .. }
    

Which one is better and why?

2

There are 2 answers

0
Ron Warholic On BEST ANSWER

I've done something like this before and I used something similar to your #2 option. When the map loads I load a configuration Lua file containing all the NPC data; among that is the name of the script file used for the NPC.

When I need to load the NPC in the game I compile the Lua file. NPC's can use a 'model' NPC type to dictate most of the common behavior (for example a Merchant type or a Commoner type) which is specified in the NPC configuration. These model types provide all the basic functionality such as providing a trade window when clicked. The specific NPC's use functions like OnClick() to override their model and provide custom handlers.

This worked pretty well for me, although it ends up being a large volume of scripts if your game gets large.

0
fouronnes On

You could use another design.

Take advantage of the fact that table keys and values can be any type.

Let's say npc is a table containing all NPC's. Its keys are NPC' names and its values are another table. This other table keys are the actions, and its values are the function for this actions. So, if you want bob to jump when clicked on, and alice to cry after a timer, simply do :

npc.bob.click = function () jump() end
npc.alice.timer = function () cry() end