Example 1 - Moving objects in Lua

Code

<scene>

	<object type="primitives://plane.aro" id="myplane">
		<event type="onclickdown">
			<runscript type="text/x-lua" code="moveThePlane()"/>
		</event>
	</object>

	<script type="text/x-lua">
	<![CDATA[ 
                  
                -- Comments in Lua are denoted using two dashes
		
		-- This code is outside of a function so happens in the first frame
		-- that the scene is shown
		
		-- The scene node is available using the scene object
		-- Use the scene object to get the node in the scene with the name "myplane"
                -- This object is global and is accessible to any of the lua in this scene
		myplaneObject = scene:getById("myplane")

                -- Functions are defined like this
		function moveThePlane()
		
                        -- This variable is local to this function and not accessible anywhere
                        -- else in the scene
			local myNewPosition = {0.5, 0.5, 0}
                        
			myplaneObject:setPosition(myNewPosition)
			
		end
	 ]]>
	</script>
</scene>

Analysis

In this simple example, the plane object is found in the scene when it starts, then a runscript node is used to run a function that moves the plane when the user clicks on it.

Note that it would be possible, and indeed preferred, to provide this simple functionality using a transition node instead of scripting. Using action nodes instead of Lua script where possible avoids the small but present performance overhead of evaluating Lua script. The next example makes use of Lua to provide functionality that is not possible with action nodes alone.