Pixel Vision 8 AddScript() Lua Tutorial

The AddScript() API allows you to add a new Lua script at runtime from a string. This could be useful for dynamically generating code such as level data or other custom Lua objects from strings or text files. Simply give the script a name and pass in a string with valid Lua code. If a script with the same name exists, it will be overwritten. Make sure to call LoadScript() after to parse it.

Usage

AddScript ( name, text )

Arguments

NameValueDescription
namestringName of the script. You don’t have to add the .lua extension.
textstringThe string representing the Lua script text.

AddScript Example

In this example, we will add a simple script that prints "Hello World" to the display. It uses AddScript() and LoadScript() to work.

Running this code will output the following:

AddScriptOutput_image_0.png

Learn more about making Pixel Vision 8 games by checking out the docs.

Step 1

Create a new file called code.lua.{1} in your project folder.

Step 2

Create a new local variable called textFile inside the script:

01 local textFile =
02 [===[
03 function test()
04 DrawText("Hello World", 1, 8, DrawMode.Tile, "large", 15)
05 end
06 ]===]

Create Lua code as a string

Step 3

Add the following code to the script:

07 AddScript("textFile", textFile)

Register the text file as a script

Step 4

Create a new function called Init():

08 function Init()
09 
10 end

Step 5

Add the following code to the script:

09   DrawText("AddScript()", 1, 1, DrawMode.Tile, "large", 15)
10   DrawText("Lua Example", 8, 16, DrawMode.TilemapCache, "medium", 15, -4)

Example Title

Step 6

Add the following code to the script:

11   test()

Call the text method

Step 7

Create a new function called Draw():

13 function Draw()
14 
15 end

Step 8

Add the following code to the script:

14   RedrawDisplay()

Redraw the display

Final Code

When you are done, you should have the following code in the code.lua file:

01 local textFile =
02 [===[
03 function test()
04 DrawText("Hello World", 1, 8, DrawMode.Tile, "large", 15)
05 end
06 ]===]
07 AddScript("textFile", textFile)
08 function Init()
09   DrawText("AddScript()", 1, 1, DrawMode.Tile, "large", 15)
10   DrawText("Lua Example", 8, 16, DrawMode.TilemapCache, "medium", 15, -4)
11   test()
12 end
13 function Draw()
14   RedrawDisplay()
15 end