Best practices for modular and scalable scripting?

Typically: "How do I... ", "How can I... " questions
Post Reply
javl0p
Posts: 10
Joined: 24 Mar 2023, 10:42

Best practices for modular and scalable scripting?

Post by javl0p »

Hello.

Along with the newer version v4.7, scripts can be objects now, which improves compartmentization of code functionalities. This actualization makes me wonder how could it be used to improve modularity and scalability of the code.

So far, I used separate .lua files for recurrent code that I would use in multiple Coppelia Scenes. I accessed them with the command require in the appropriate child script. However, this method had its limitations since scripts were very static and i had to make sure the scene's object names and hierarchies matched as stated in the scripts.

With the addition of script objects, it is possible to copy/paste code objects from one scene to another, and to customize the script object of each scene.
  • However, I wonder what is the best way to hadle this code. Is there a way to save the script objects and load them in a similar way to .ttm models?
  • Should I keep using the same old method of script calling via the require command?
  • Is there a better way to handle this?
Thanks in advance!

coppelia
Site Admin
Posts: 10504
Joined: 14 Dec 2012, 00:25

Re: Best practices for modular and scalable scripting?

Post by coppelia »

Hello,

for code you want to reuse, it is really best to have a separate *.lua file and to include that file via a require directive. With the require directive you can include the whole code, or just specific code and still have a script body inside of the script object.

You can of course also save/load script objects as you'd do with any other model. Just remember to tag your script object as model base, otherwise you won't be able to save it as a model.

You can of course also dynamically create new script objects as in following example:

Code: Select all

    local code = [=[ 
    -- some multi-line lua code
]=]

    local script = sim.createScript(sim.scripttype_customization, code, 0, 'lua')
    sim.setObjectAlias(script, 'myLuaScript')
    sim.initScript(script)
Cheers

Post Reply