Lua Scripting C

  1. Lua Scripting C++
  2. Lua Scripting App
  3. Lua Scripting C Code
  4. Lua Scripting Classes Roblox
  5. Lua Scripting Course Free

3.2. System library

DynamicLua is based on NLua, which can do all of this as well, but it will be more complicated. (1) Download ActiveState TCL and install. (2) Copy File C: Tcl bin tcl86.dll and C: Tcl bin zlib1.dll to the place where your C# exe is located for your application, most likely under 'Debug' directory.

This library contains various system functions.

It provides all its functions inside the table SysUtils.

System library
Function nameDescription

SysUtils.Sleep(Milliseconds)

Suspends the execution of the script for the specified number of Milliseconds.
After the specified period has expired, script execution resumes.

SysUtils.GetTickCount

SysUtils.GetTickCount()

Returns an increasing clock tick count. It is useful for time measurements, but no assumtions should be made as to the interval between the ticks.

bFlagExists = SysUtils.FileExists(FileName)

Check whether a particular file exists in the filesystem.

Returns in bFlagExists the value true if file with name FileName exists on the disk, or false otherwise.

SysUtils.DirectoryExists

bFlagExists = SysUtils.DirectoryExists(Directory)

Checks whether Directory exists in the filesystem and is actually a directory.

If this is the case, the function returns in bFlagExists the value true otherwise false is returned.

Attr = SysUtils.FileGetAttr(FileName)

Returns in Attr the attribute settings of file FileName.

See the detail explanations of the returned value here.

SysUtils.FindFirst

Handle, FindData = SysUtils.FindFirst(Path)

Looks for files that match the Path, generally with wildcards.

If no file is found, Handle will be nil.

When at least one item is found, the returned Handle may be used in subsequent SysUtils.FindNext to find other occurences of the same pattern.

The FindData table contains information about the file or directory found.

The field of the FindData table are:

  • Name : The file name (without path).
  • Attr : The file attributes of the file (see details here).
  • Size : The size of the file in bytes.
  • Time : The time stamp of the file (seconds since Jan 01 1970)

Result, FindData = SysUtils.FindNext(Handle)

Finds the next occurrence of a search sequence initiated by FindFirst by re-using the Handle returned previously.

Returned Result will be non-nil if a file or directory is found and will be nil otherwise.

The same notes mentionned for SysUtils.FindFirst applied here.

Remark: The last SysUtils.FindNext call must always be followed by a SysUtils.FindClose call with the same Handle. Failure to do so will result in memory loss.

SysUtils.FindClose

SysUtils.FindClose(Handle)

Ends a series of SysUtils.FindFirst/SysUtils.FindNext calls.

Frees any memory used by these calls.

It is absolutely necessary to do this call, or memory losses may occur.

bResult = SysUtils.CreateHardLink(Path, LinkName)

Create the hard link LinkName to file Path.

Returns true if successful, false otherwise.

SysUtils.CreateSymbolicLink

bResult = SysUtils.CreateSymbolicLink(Path, LinkName)

Create the symbolic link LinkName to file or directory Path.

Returns true if successful, false otherwise.

sTarget = SysUtils.ReadSymbolicLink(LinkName, Recursive)

Read destination of the symbolic link LinkName.

If Recursive is true and the link points to a link then it's resolved recursively until a valid file name that is not a link is found.

Returns the path where the symbolic link LinkName is pointing to or an empty string when the link is invalid or the file it points to does not exist and Recursive is true.

SysUtils.PathDelim

SysUtils.PathDelim

Allows a script to get from DC the system path delimiter.

In Unix/Linux system will be a ' / ' and in Windows will be ' '

sName = SysUtils.ExtractFileName(FileName)

Extract the filename part from a full path filename.

The filename consists of all characters after the last directory separator character ('/' or ') or drive letter.

SysUtils.ExtractFilePath

sPath = SysUtils.ExtractFilePath(FileName)

Extract the path from a filename (including drive letter).

The path consists of all characters before the last directory separator character ('/' or '), including the directory separator itself.

sDir = SysUtils.ExtractFileDir(FileName)

Extract only the directory part of FileName, including a drive letter.

The directory name has NO ending directory separator, in difference with SysUtils.ExtractFilePath.

SysUtils.ExtractFileDrive

sDrive = SysUtils.ExtractFileDrive(FileName)

Extract the drive part from a filename.

Note that some operating systems do not support drive letters.

sExt = SysUtils.ExtractFileExt(FileName)

Return the extension from a filename (all characters after the last '.' (dot), including the '.' character).

SysUtils.CreateDirectory

bResult = SysUtils.CreateDirectory(Directory)

Create a chain of directories, Directory is the full path to directory.

Returns true if Directory already exist or was created successfully. If it failed to create any of the parts, false is returned.

Contents

  • What to get?

  • Installing

  • Basic Use of Lua

  • A notch, a crank, knarc, ahctona!

  • But wait! There's more amazing where that came from!


Lua allows us to easily add scripting to our game. It's a well known, widely used standard (it was used in Balders Gate). Once added it can process both compiled and uncompiled Lua scripts giving a good combination of flexibility and strength. The greatest advantage to Lua is how simply we can insert it into our C# programs. Well, hopefully now your convinced so let's get cracking.

What to get?


LuaInterface 1.3

Installing


Unzip LuaInterface 1.3 (or later version that you may have been able to download). Put it somewhere safe such as in the Visual Studio directory or some place your unlikely to accidentally delete.
Now boot up visual studio. Create a new C# Console Project.
Now go to the Solution Explorer window.
(If you can't see it use this
and it should pop up!) Take your mouse over to the References icon and right click.
Choose add reference. This should all be pretty standard fare for starting a new project. We're just recovering the basics here in case you're reading this tutorial as a seperate chunk.
Carefully survey your options and then choose 'Browse'. Then browse to where you unzipped LUA and go into the bin folder ... and select LuaInterface.dll. My copy of this .dll file is at the following location C:LuaInterfacebinLuaInterface.dll.
Once you have chosen this .dll file it will pop up in the the 'Selected Components' part of the window. Confirm the selection and we're ready to go. I'm sure there's a method of playing with Visual Studio where you can avoid the 'Browse' button all together and have the reference preloaded in, ready to select but after a few minutes fiddling I couldn't find it :(
Your game and your game players are going to need access to the Lua dll files. So you need to have them in project directory. My version of the console application executable that we're working on is currently located here: junkVisual Studio ProjectsConsoleApplication3binDebug

Lua Scripting C++

Open up that directory. Also open up the directory of were you installed Lua. Go into the bin directory and copy across (to project directory):
Your working directory should end up looking a little like this:
That concludes setting up Lua to work with this project. Not too painful.

Basic Use of Lua


Let's write some code. We want to make a C# program that's interfaces with Lua and we want to do it soon, very soon indeed.Free


The above is our class skeleton. The only thing worth noting at the moment is that we're using the LuaInterface reference. We'll concentrate on the main method an make a small program that uses Lua.



Here we create a Lua interpreter. We can create as many as we wish and they will all be independant. But for now we'll only have one.



Next we create some global variables. Remember we're programming in a scripting language so we're creating Lua global variables not C# global variables. In actual use this 'programming' would be done ahead of time and then loaded in from a file. Curently we're doing it directly in the code just to get a feel of what's happening.



This creates two Lua global variables. One is called num the other is called str. Note that the variables both hold different types. This is a feature of Lua it is not a strongly typed language in fact it's dynamically typed. Variables can be anything (though Lua only has a few data types). But I don't want to get pulled in to a distracting explanation of how Lua works as a programming language quite just yet. First I'd quite like to get it hooked up to C#.



Now we made these Lua varaibles let's get C# to read them. Now as you really should know by now C# is a strongly typed language. So we need to cast the variables.



Note that we must cast to a double here. An int won't cut it as Lua is storing double information. Now we've read this information out from the Lua interpreter, next let's read it out to the screen to see if everything is agreeable.



Okay so far not very exciting but we're still only getting a feel of what's going on. So let's crank it up a notch next and do something cool.


A notch, a crank, knarc, ahctona!



Okay grip the arms of your chair tightly and get ready to script!



First let's create two functions we might like our brand new scripts to make use of.



Feel free to insert your own name instead of Dan or Thor. So now we have two cool functions bursting with game playing potential.



Let's hook them into Lua - so out main method will look like below:



This lets the Lua scripting language make calls to our two C# functions. Incredibly easy isn't it? So in the Lua language we just make calls to DanSays('with a nice string here') or ThorSays('with an equally nice string here') and they will call the C# equivalents!


The RegisterFunction function



The RegisterFunction's first argument is what you'd like to name the function in Lua. Here we chose the same name because it's so simple. But in future function registration we might want to make the Lua name more simple or descriptive than our C# name.



The second argument is the object where the method is stored. Note the word object. That's why we have to instantiate our Program program. So if we have a class called person 'Class Person' and it has a method talk then it allows us to do something like.



We can the register these talk functions seperately.



The third parameter uses reflection - something I currently know nothing about. All I know is that's it's magic like pixey dust and elevators. It magically gets all the knowledge about the method - it's arguments and so forth. Then Lua can call it effectively. You have to pass in a string of the methods name and that's it. Great!


The DoString function


Add this to the end of our main method.



DoString executes a line of Lua code in string form. Wonderbar!


But wait! There's more amazing where that came from!



So we've got a pretty groovy scripting language all by doing relatively little.



But now let's arrange it into a bit more of a game like usefullness. Go to your working directory for this project. The place where you copied all those dll files (mine is: My DocumentsVisual Studio ProjectsConsoleApplication3binDebug).



Okay create a new directory all call it 'scripts'


Now in the scripts directory I've created a simple text file called 'Thursdays'
It has the following not-so-witty-banter.
Okay. So in scriptsThursdays.txt

Lua Scripting App

with have some future-award-winning dialogue. It's written in Lua but only using custom functions designed by us because we're cool and groovy designers.

Back to El Code


Make your main method match mine pictured below:
This fine piece of programming hereafter known as 'ScriptRunner3000' will run any script we call Thursdays - without recompling - yes you heard me correctly - without recompiling!
Of course if we want to get really fancy we could write some code to enumerate all the files in scripts and then produce a menu allowing you to choose which you'd like to use. But this is much more of a proof of concept deal. Anyway the output:
Now the script can be tinkered with to our hearts extent and the exutable will show those changes without having to be run. Of course it's a lot more powerful than it is here. We can uses Lua's code constructs like loops and structures and all those niceities - wasn't putting a scripting engine in really simple? :o
Now you should brush up your Lua!

Globals


Lua is simple and powerful I just wanted to show persistancy of globals then maybe we'll end this tutorial here. But later come back to really really groovy things like coroutines.
If in Thursdays.txt we now include the line name = 'rabbits' then the above code will outpt rabbits. See the scope isn't lost in the file which is super groovy and allows us to easily insert scripts into the game loop - yay!

Lua Scripting C Code

Source Code


Download the source code.

Lua Scripting Classes Roblox


References used

Lua Scripting C

Lua Scripting Course Free


  • LuaInterface: User’s Guide by Fabio Mascarenhas

  • LUA 5.0 Reference Manual (avaliable from www.lua.org)