Lua C Weapon Script

  1. Lua C Weapon Script Pastebin
  2. Lua C Weapon Scripts

If glo then GlowMesh (false,'Sphere',t,v3 (glo,glo,glo),'Navy blue',cn (bpos),0.1,1,0.08) end. If fu and bhit then fu (bhit) else wait (rn (0,20)/10) fade (v,0.1) end. Function ProjHit1 (v,hit,mul2) local mul = mul2 q (function if not mul2 then mul = 1 end if not hit.Anchored then.

All scripts should have a function Base_Definitions defined, either directly or in one of their required scripts. This is called by the engine when the script is first loaded.

  • The process of connecting a native language, such as C, with a scripting language is called binding. In the Lua case, its API provides functions that help you expose native functions to the script code. So you can for example define a C function sayhello and make this function callable from a Lua script.
  • To start with lets create a very basic Lua script and save it as 'script.lua': - Start - Script: script.lua print('I am using Lua from within C') - End There, told you it was a very basic script! When we embed Lua into C, we will ask Lua to open and run that file. For more examples, see the end of the tutorial. Now for the C code.

Contains all galactic AI plans as well as subfolders 'LandMode' and 'SpaceMode' which contain the plans for the corresponding game modes.Note that scripts in this folder are only recognized by the game if they are in the main game directory (i.e. not in a mod folder) or if a script of the same name is contained in a loaded .meg file. In the latter case the script from this folder overrides the one in the .meg.

Scripts in this folder can be invoked by perceptions to run Lua commands to compute something. They contain a function Evaluate which is called when a perception invokes the script. Its return value is passed back to the perception.They also contain a function Clean_Up to reset variables containing pointers. The engine will actually call Evaluator_Clean_Up which is implemented in PGBaseDefinitions and calls Clean_Up.

The scripts in this folder handle the AI freestore, i.e. they control those units that are not needed for any active AI plans.

Contains scripts that are attached to units with the Lua_Script tag. The game loads several instances of these scripts at once (given by the ScriptPoolCount) even if not all of them are needed. Each unit is assigned its own script instance. When a unit with a script dies, rather than discarding and reloading the script the game cleans up the script instance by calling Flush_G and Base_Definitions again and assigns it to the next unit that requires it.The main function is called when the unit is spawned. Usually, object scripts simply require PGStateMachine which implements the main function and offers state machine functionality instead.Object scripts require the variable ServiceRate to be set in the setup phase, otherwise the main function won't be run.

Here, the base game intervention scripts are defined. They are simply AI plans for the player that use some specific logic.

This folder contains library scripts that do not have a specific purpose on their own but rather provide common base functionality for other scripts.


Contains commands for debugging which are deactivated for the release build.

DebugEventAlert(event, params)event, list of parametersTriggers a MessageBox with information on the event and parameters.
MessageBox(..)String and optionally values for formattingTriggers a MessageBox with the formatted string.
ScriptMessage(..)String and optionally values for formattingLogs the formatted string in the AI log.
DebugMessage(..)String and optionally values for formattingLogs the formatted string in the AI log.
OutputDebug(..)String and optionally values for formattingLogs the formatted string in the log file.
ScriptError(..)String and optionally values for formattingLogs the formatted string in the log file and the AI log and exits the script.
DebugPrintTable(unit_table)tablePrints all values to the AI log.


Requires PGDebug. Defines some basic functionality.

ScriptExit()-Immediately terminates the script without executing any other statements.
Sleep(time)time in secondsContinue pumping events without doing anything else until the given game time has passed.
BlockOnCommand(block, max_duration, alternate_break_func)block: an object that has methods IsFinished and ResultWaits until block.IsFinished() returns true, alternate_break_func() returns true or the given time runs out. If the block has finished, this returns block.Result(). Mainly used for unit movement commands and the reinforce command.
max_duration in seconds (optional)
alternate_break_func (optional)
BreakBlock()-Breaks a BlockOnCommand (may have unexpected effects if a BlockOnCommand is running in multiple threads)
TestCommand(block)block: an object that has a method IsFinishedRuns PumpEvents once and returns block.IsFinished()
PumpEvents()-Implements threading and calls event handlers. Returns control to 'C' and continues on next service (i.e. after ServiceRate seconds).
TestValid(wrapper)wrapper: nil, game objectUsed to check validity of game objects. Returns false if wrapper is nil, doesn't have a function Is_Valid or wrapper.Is_Valid() is false.
Clamp(value, min, max)value, min, max: numbers
Dirty_Floor(val)val: numberReturns val as string. Requires implicit string to int conversion of the return value.
Simple_Mod(a,b)a,bModulus function.
Chance(seed, percent)seed, percentRequires a random seed between 0 and 99. Under those conditions it returns true with percent chance.
GetAbilityChanceSeed()-Just the current game time in seconds
GetChanceAllowed(difficulty)-Supposed to be difficulty dependent but always returns 100
PlayerSpecificName(player_object, var_name)player_object, var_name(string)Returns var_name with a player specific prefix
Flush_G()-Used to reset object scripts. Deletes all tables except for a few 'very important' ones. Also deletes most userdata.


Requires PGBase. Mainly defines/resets commonly used variables but also some additional functions.

Common_Base_Definitions()-(Re)Sets all kinds of global variables. Only used in Base_Definitions()
Base_Definitions()-Calls Common_Base_Definitions() and Definitions() if it exists.
Evaluator_Clean_Up()-Basic clean up function for evaluator scripts. Calls Clean_Up().
UnitListIsObscured(unit_list)unit_listReturns true if all given units are obscured by some space field.
Cull_Unit_List(unit_list)unit_listRemoves all dead or otherwise invalid units from a list and returns it.


Requires PGBaseDefinitions. Contains functions to set callbacks for certain events and some advanced unit/taskforce functionality.

WaitForever()-Wait forever ..
Register_Timer(func, timeout, param)func, timeout, param(optional)Sets up a callback func(param) after timeout (in seconds) has expired.
Process_Timers()-Internal function to manage timers.
Cancel_Timer(func)funcCancel timer for a given function.
Register_Death_Event(obj, func)obj, funcSets up a call to func when the given object dies.
Process_Death_Events()-Internal function to manage death callbacks.
Register_Attacked_Event(obj, func)obj, funcSets up a call func(true, attacker, obj) when the given object is first attacked and a call func(true, nil, obj) when the given object is no longer under attack. The callback is not cancelled automatically at any point.
Process_Attacked_Events()-Internal function to manage attack callbacks.
Register_Prox(obj, func, range, player_filter)obj, func, range, player_filter(optional)Sets up a callback to func(obj, trigger). The callback is executed continuously if not cancelled. Cancel by calling obj.Cancel_Event_Object_In_Range(func).
Process_Proximities()-Internal function that calls Service_Wrapper on units registered for proximity callbacks.
Pump_Service()-Internal function that runs processing functions and Story_Mode_Service if it exists. Is called by PumpEvents.
Try_Ability(thing, ability_name, target)thing, ability_name, target(optional, depends on ability)thing can be a unit or taskforce. Activates ability if possible. Only activates ability if an ability dependent chance is successful. However, in vanilla that chance is always 100%.
Use_Ability_If_Able(thing, ability_name, target)thing, ability_name, target(optional, depends on ability)thing can be a unit or taskforce. Activates ability if possible.
ConsiderDivertAndAOE(object, ability_name, area_of_effect, recent_enemy_units, min_threat_to_use_ability)object, ability_name, area_of_effect(number), recent_enemy_units(unit list), min_threat_to_use_ability(number)This will consider diverting the passed object in order to use an area of effect ability centered on the unit.
OneOrMoreInRange(origin_unit, target_unit_list, range)origin_unit, target_unit_list, rangeReturns true if at least one of target_unit_list is inside the given range of origin_unit
PruneFriendlyObjects(obj_table)obj_tableRemoves any objects in obj_table that do not belong to PlayerObject and returns them in a new list.
Try_Garrison(tf, unit, offensive_only, range)tf(optional), unit, offensive_only, rangeTries to garrison unit. Prefers places from which the unit can fire but will also find others if offensive_only is false. If tf is given, releases unit from tf.
Try_Deploy_Garrison(object, target, health_threshold)object, target(optional), health_threshold(number)Deploys units garrisoned in object if their health is high enough and there is no target or the garrisoned unit is good against the target.
Get_Special_Healer_Property_Flag(unit)unitDefines which heroes are healed by which type of healer. Also done for some special units. Used in free store and PGEvents.
Set_Land_AI_Targeting_Priorities(tf)tfSets targeting priorities for the given taskforce.
Try_Weapon_Switch(object, target)object, targetSwitches weapons if they are more effective against the given target. Requires a custom entry for each unit type that can switch weapons.
Determine_Magic_Wait_Duration()-Returns a wait duration for magic plans.


Requires PGCommands. Overrides Base_Definitions and sets values used in AI scripts. Also defines unit category contrast values for the AI.

Base_Definitions()-Calls Common_Base_Definitions, sets some AI plan variables and resets taskforce variables. Also calls Definitions if it exists.
Set_Contrast_Values()-Tells the AI how effective unit categories are against others.


Requires PGAICommands. Defines taskforce functions for AI scripts.


Requires PGTaskForce. Defines default event handlers for taskforces and some helper functions.


Requires PGCommands. Implements a state machine.


Requires PGStateMachine. Uses the state machine to handle story events.


Requires PGBaseDefinitions. Defines functions to use movement commands for unit lists.


Requires PGBaseDefinitions. Defines functions for reinforcing and to spawn a list of units.


Requires PGBaseDefinitions. Basic setup and helper functions for interventions.


Lua C Weapon Script Pastebin

GameScoring, FleetEvents and random stuff

This is where all story scripts are as well as the .txt files that define the story logs.

Lua Scripts

Scripts in here can be used for GCs or tactical missions by setting them in a story plot .xml file. Base_Definitions for these scripts is called during load of the GC/tactical mission. main is called when the respective game starts, however story scripts usually rely on PGStoryMode and PGStateMachine rather than implementing their own main functions.Unlike object scripts, story scripts don't pool and are discarded when the game mode ends. As such, they are reloaded directly from the file when they are needed again.

Dialog files

The dialog files in this folder are simple text files with a specific syntax that define the story log entries in GC. The first entry starts with [CHAPTER 0], comments start with #.

TITLETextfile StringThe title shown directly over the main text body, not what is shown in the list of log entries.
MOVIEMovies.xml entry
WAITNumber (or SPEECH?)
SFXSfx event xml namePlay SFX.
TEXTCOLORFour numbers 0-255Set text color of any text entries below this command using rgba color format.
TEXTTextfile StringDisplay textfile entry.
NEWLINENumberAdd given number of empty lines
DIALOGSpeechEvent xml name

EDIT: Part 2

Long time without posting, busy at work, family, etc.

Today I decided to write a bit on Lua and how to integrate it with C++.

Lua is a scripting language with an emphasis on being easily embeddable. Lua isused as the scripting language in Photoshop CS, and World of Warcraft, forexample. So if you are looking into adding scriptability to your C or C++applications Lua is quite suited for the task.

In order to learn Lua (both the language itself and how to embed it into yourapp) I recommend you Programming in Luaby one of the Luaauthors.

You can find tons of tutorials on how to get started with Lua. So I will focushere on how to integrate with C++. Most of the sources I’ve found about Lua -C++ integrations take the approach of frameworks to automatically wrap yourobjects/classes to be usable from within Lua. I find this approach confusing, Ithink it’s better to learn how to do it manually, and that’s what I will dohere.

Step 0. Compile Lua itself

Download Lua 5.2.1 and compile it. Usually it enough with make macosx ormake linux. That will generate liblua.a, the library that we will link to.

Step 1. Create a simple host app

We need a simple host app. Our host app will simply setup Lua and run a scriptfrom it. This script will have access to a std::queue from the host app. Thiswill illustrate how you can share objects with the Lua part. Later we will takea more complex example.

Let’s start with the basic skeleton of a lua environment with somecommunication with its host:

The Makefile

It uses LUAHOME that should point to the directory containing both liblua.a and the lua*.h files.

The samplehost application

The Lua script

The code explained step by step:


That creates a lua_State loads the standard libs in it and also loads the code in luascript.lua.

Adding variables from C++ into Lua

Then it sets a global variable in Lua from C++ code using lua_setglobal. Ifyou don’t know what are the lua_pushxxxx and the Lua stack, etc. I recomentthat you take a look at the Lua Reference Manual and Programming in Lua.More or less Lua and the C++ communicate through the stack that livesin lua_State and there is bunch of function to manipulate that stack. So inorder to set a global in Lua from C++ you must push the value into the stackand call lua_setglobal that will pop the value in the stack and assign it tothe identifier provided inside the Lua environment.

After setting the global cppvar it executes the loaded chunk of code (that is in the stack) with lua_pcall. The Lua code is able to read and print the value of cppvar. The lua code will also set a new global luavar that we will access from C++.

Reading a Lua variable from C++

To get luavar from C++, we must first use lua_getglobal that will put the value associated with the identifier into the top of the stack and the lua_tonumber will transform whatever it’s at the top of the stack into a double (well a luaNumber) and then we can use that double in our C++ code to print it.

Calling a Lua function from C++

The example won’t be complete without function calling so that’s the next step.Calling a Lua function from C++ it’s quite easy. Function in Lua are firstclass values, so that means that it’s just a like reading a any other value.lua_getglobal will get the value and put it on the stack and then we push thefunction arguments into the stack and use lua_pcall to call the function(that is the stack). The returned value from the function will be pushed in thestack and that’s were the C++ code will get it, lua_tostring and then it willremove from the stack with lua_pop.

Calling a C++ function from Lua

The other way around it’s more complex. You can’t just call any function fromLua. Gta v serial key for free. It has to has a special signature lua_CFunction, that is, typedef int(*lua_CFunction) (lua_State *L) a function that returns an int and takes alua_State. This special funciton will communicate with Lua via the lua stackthat resides in the lua_State parameter. The return value of the functiontell lua how many value the function has pushed into the stack as result valuesfor the function call.

So to make the function accesible from Lua, you create push the function intothe stack with lua_pushcfunction and bind it to an identifier in lua withlua_setglobal. Then lua code will be able to invoke this function like anyother function. In the example I call the myfunction (which is lua code) andmyfunction in turn invokes cppfunction which is “bound” to C++l_cppfunction. Ah, I almost forgot. l_cppfunction is declared as extern'C' telling the compiler to provide C linkage for this function so it can becalled from a C library like Lua is.

Free Lua resources

lua_close will free all resources held by the lua_State L.

Wrap up

Lua C Weapon Scripts

I will leave the part on how to wrap C++ class objects inLua for a later post because Idon’t want to make this post too long. Hopefully I’ll post it tomorrow.