Passing arguments to scripts

Introduction

Providing arguments to the script

In many cases, it will be useful to provide your scripts with arguments. For example, for choosing the name of an element, the color of a material or whatever other parameter you may be interested in.

Emp allows providing arguments to your scripts. This is easily done by writing all the arguments after the command

emp - script Argument1 Argument2 ...

Lets write a script called Hello.lua that takes advantage of this:

-- We tell Emp that we will not make calculations
auto_solve = false 

-- capture the first argument.
-- The second argument will be stored in argv[2], and so on.
name = argv[1]

-- Greet
print("Hello",name)

And run it

emp - Hello.lua John

And the results are

Dealing with absence of argument

Sometimes people make mistakes and do not provide a certain argument. For example, run the Hello.lua script without a first argument

The result is

That means that that the variable name was not initialized, which could cause a big error in other sections of the code or Emp. Lua provides at least two very simple ways of dealing with this, which are explained belo.

Throwing an error

One option is to check if the element is nil, and do something about it (e.g. raise an error)

Running this script without an argument throws an error

In any other case it will greet

Default values for arguments

Another option is to set a default value to such argument.

Running this script without an argument prints Hello Jim; in any other case, it will greet as expected.

Last updated