Porting AMX Mod X plugins
Classic Strike runs plugins written in Luau on its own API (docs/plugins_api.md, docs/plugins_reference.md). Plugins written for AMX Mod X can be ported in two ways:
-
**On
compat/amxx**: the AMXX functions under their own names and meanings, so a port stays close to the original line by line. - On the API directly: shorter and faster code; the right choice for new plugins and for ports that are rewritten anyway.
The two mix freely: a port on compat/amxx can call cs.* anywhere.
compat/amxx is written from AMX Mod X's public documentation (what each function is called and what it does), never from its code.
Starting a port
local amxx = require("compat/amxx")
local function plugin_init()
amxx.register_plugin("Hello", "1.0", "Me")
amxx.register_clcmd("say /hello", "cmd_hello")
end
local function cmd_hello(id)
amxx.client_print(id, amxx.print_chat, "Hello %n", id)
return amxx.PLUGIN_HANDLED
end
amxx.publics({ plugin_init = plugin_init, cmd_hello = cmd_hello })
amxx.publics{} lists the plugin's public functions: the forwards it has (plugin_precache, plugin_init, plugin_cfg, plugin_end, client_connect, client_authorized, client_putinserver, client_disconnected, client_disconnect, client_infochanged, client_command, client_PreThink, client_PostThink, server_frame) and the callbacks other functions take by name (set_task("fn"), menu_create(title, "handler")). plugin_precache runs at each map's start; plugin_init and plugin_cfg once, after it (at once when a map is running already).
Conventions
-
Indexes: players and entities are numbers, as in AMXX (players 1..
get_maxplayers(), 0 for the server). - Out-parameters become results: what a Pawn function writes into variables comes back as results, in their order.
| Pawn | Luau |
|---|---|
get_user_name(id, name, charsmax(name)) | local name = amxx.get_user_name(id) |
get_players(players, num, "ach") | local players, num = amxx.get_players("ach") |
get_user_origin(id, origin) | local origin = amxx.get_user_origin(id) (a vector) |
new wid = get_user_weapon(id, clip, ammo) | local wid, clip, ammo = amxx.get_user_weapon(id) |
read_argv(1, arg, charsmax(arg)) | local arg = amxx.read_argv(1) |
-
Vectors: three numbers (origins, angles, velocities) are a
vector. -
Strings are Luau strings; lengths (
charsmax) are dropped. - Callbacks are a function or the name of a public.
-
Formatting:
format,client_printand the rest take the Pawn specifiers (%d %i %u %f %.2f %s %a %c %x %X %o %b %n %N %L %%, with flags, width and precision).%Lreads the plugin'slang/<language>.toml(register_dictionaryhas nothing to load):LANG_PLAYERis the player the text goes to, so a message to everyone is formatted for each player. -
Chat colours:
client_print_colorand the^1(default),^3(team) and^4(green) bytes work as in AMXX;cs.chatalso reads the{green},{team}... tags. -
Admin flags: the letters of
users.iniare theadmins.tomlpermissionsamxx:<letter>(immunity counts asa); a player who is no admin hasADMIN_USER.access,get_user_flags,cmd_accessandset_user_flagswork on them. -
No equivalent: a function that has none (memory offsets,
get_pdata_*with numeric offsets, signatures, binding a Pawn variable to a setting) raises an error that says what to use instead.
Coverage
amxmodx
| Area | Functions |
|---|---|
| Plugin | register_plugin, get_plugin_info, the forwards above |
| Commands | register_clcmd, register_concmd, register_srvcmd, read_argc, read_argv, read_argv_int, read_argv_float, read_args, remove_quotes, cmd_access, cmd_target |
| Settings | register_cvar, create_cvar, cvar_exists, get/set_cvar_num/float/string, get/set_pcvar_num/float/bool/string, hook_cvar_change |
| Tasks | set_task (flags a and b), remove_task, task_exists, change_task |
| Text | format, formatex, client_print, client_print_color, console_print, server_print, log_amx, log_message, log_to_file, server_cmd, client_cmd, console_cmd, register_dictionary |
| Players | get_user_name/authid/ip/userid/index/team/health/armor/frags/deaths/ping/time/origin/aiming, get_players, get_playersnum, find_player, is_user_connected/alive/bot/hltv/admin, user_kill, user_silentkill, user_slap |
| Admin | read_flags, get_flags, get_user_flags, set_user_flags, remove_user_flags, access, is_user_admin |
| Weapons | CSW_*, get_weaponname, get_weaponid, get_user_weapon, get_user_weapons, get_user_ammo |
| Server | get_mapname, get_maxplayers, get_time, get_timeleft, get/set_localinfo, precache_model/sound/generic, random_num, random_float, floatround |
| Strings | the string functions (equal, equali, contain, containi, replace, replace_all, parse, strtok, trim, str_to_num, num_to_str...) |
| HUD | set_hudmessage, show_hudmessage, CreateHudSyncObj, ShowSyncHudMsg, ClearSyncHud, set_dhudmessage, show_dhudmessage |
| Menus | register_menuid, register_menucmd, show_menu, get_user_menu; newmenus: menu_create, menu_additem, menu_addblank, menu_addtext, menu_items, menu_pages, menu_item_getinfo, menu_item_setname/setcmd/setcall, menu_setprop, menu_destroy, menu_display, menu_cancel, menu_makecallback, player_menu_info |
| Userinfo | get_user_info, set_user_info (taken in the next frame: name renames), SetGlobalTransTarget with %l |
| Maps, MOTD | is_map_valid, show_motd (a file of the data folder or the text), user_has_weapon |
| Floats | floatsin/cos/tan/asin/acos/atan/atan2 (with radian, degrees, grades), floatsinh/cosh/tanh, floatlog, floatmax, floatmin, floatclamp, floatfract |
| xs | the vector and number stocks: xs_vec_set/copy/add/sub/add_scaled/sub_scaled/mul_scalar/div_scalar/neg/len/len_2d/normalize/distance/distance_2d/sqdistance/dot/cross/equal/nearlyequal/angle/reflect/make2d, xs_sqrt, xs_rsqrt, xs_abs, xs_sign, xs_deg2rad... |
| celltrie | TrieCreate, TrieSet/GetCell/String/Array, TrieKeyExists, TrieDeleteKey, TrieClear, TrieGetSize, TrieDestroy, TrieSnapshot*, TrieIter* |
| cellarray | ArrayCreate, ArrayClone, ArrayClear, ArraySize, ArrayResize, ArrayGet/Set/Push/InsertArray/Cell/String, ArraySwap, ArrayDeleteItem, ArrayFindString, ArrayFindValue, ArraySort, ArraySortEx, ArrayDestroy (items from 0) |
| Files | fopen (r, w, a, +), fclose, feof, fgets, fputs, fprintf, fputc, fgetc, fseek, ftell, fflush, fread, fwrite, fread_blocks, fwrite_blocks, read_file, write_file, file_exists, file_size, delete_file, rename_file, mkdir, dir_exists, rmdir, open_dir, next_file, close_dir, get_datadir, get_configsdir, get_basedir |
| Natives | register_native (styles 0 and 1), register_library, get_param, get_param_f, get_param_byref, set_param_byref, get_string, set_string, get_array, set_array, LibraryExists; plugin_natives runs first |
| Forwards | CreateMultiForward (ET_IGNORE, ET_STOP, ET_STOP2, ET_CONTINUE), CreateOneForward, ExecuteForward, DestroyForward, PrepareArray; callfunc_begin, callfunc_begin_i, get_func_id, callfunc_push_*, callfunc_end |
| Plugins | is_plugin_loaded, find_plugin_byfile, get_pluginsnum, get_plugin |
No equivalent: bind_pcvar_* (read the setting with get_pcvar_*, or keep a copy current with hook_cvar_change).
Files live in the plugin's data folder (plugin_data/<plugin>/): a leading addons/amxmodx/ goes, so get_datadir() (addons/amxmodx/data) names its data/ and the configs a plugin reads go in its configs/; characters the data folder does not take become _. A file opened for writing is written when it is closed or flushed. Files have no time stamps (GetFileTime).
Natives and forwards cross plugins: a plugin on compat/amxx that calls a native it does not have finds the plugin that registered it (any loaded one) and gets its result and then the parameters as the handler left them (cs_port writes them back into the caller's variables); ExecuteForward and callfunc_* run the public in each plugin on compat/amxx that has it. Values are copied between the plugins.
Behaviour notes:
-
A
saycommand (register_clcmd("say /x", ...)) matches when the chat line is exactly/x. -
PLUGIN_HANDLEDfrom a client command stops the game from handling it. -
A handler added in a forward hears the changes made after the forward returns (
hook_cvar_changeinplugin_initdoes not see a change made later in the sameplugin_init).
fakemeta and engine
Entity variables go through raw access by their classic names, so a port that uses them needs permissions = ["raw_properties"] in plugin.toml. Each classic name (pev_health, EV_FL_health, EV_ENT_owner) is a constant naming itself; the names are in docs/plugins_fields.md.
| Area | Functions |
|---|---|
| Variables | pev, set_pev (a vector, a table or three numbers), set_pev_string, pev_valid, entity_get/set_int/float/vector/string/edict/byte |
| Entities | create_entity, remove_entity, is_valid_ent, entity_count, entity_set_origin/model/size, DispatchSpawn, DispatchKeyValue, force_use, drop_to_floor |
| Finding | find_ent_by_class/tname/target/model/owner, find_ent_in_sphere, find_sphere_class |
| Traces | trace_line, trace_hull, trace_normal, point_contents, create_tr2, free_tr2, get_tr2, set_tr2, get_tr, set_tr |
| Vectors | angle_vector, vector_length, vector_distance, get_distance(_f), vector_to_angle, entity_range, get_speed, velocity_by_aim, get_user_button, get_user_oldbutton |
| engfunc | PrecacheModel/Sound/Generic, SetModel, SetSize, SetOrigin, AllocString (gives the string back), CreateNamedEntity, RemoveEntity, FindEntityByString, FindEntityInSphere, TraceLine, TraceHull, TraceModel, TraceTexture, PointContents, EmitSound, MakeVectors, DropToFloor, GetInfoKeyBuffer, InfoKeyValue, Time, ServerCommand, NumberOfEntities, EntIsOnFloor |
| dllfunc | Spawn, Use, KeyValue |
| Globals | global_get (glb_time, glb_frametime, glb_maxClients, glb_mapname, glb_v_forward/right/up, the glb_trace_*) |
| Forwards | register_forward / unregister_forward: FM_Spawn, FM_Think, FM_Touch, FM_Use, FM_Blocked, FM_PlayerPreThink, FM_PlayerPostThink, FM_ClientConnect, FM_ClientPutInServer, FM_ClientDisconnect, FM_ClientUserInfoChanged, FM_ClientCommand, FM_CmdStart (get_uc/set_uc), FM_EmitSound, FM_StartFrame, FM_AddToFullPack (get_es/set_es) |
| engine callbacks | register_think, register_touch, register_impulse and their unregister_* |
| Constants | MOVETYPE_*, SOLID_*, DEAD_*, DAMAGE_*, kRender*, USE_*, IN_*, FL_*, EF_*, DMG_*, CONTENTS_*, HULL_*, CHAN_*, ATTN_*, FMRES_* |
Each forward runs on an event of the event model (docs/plugins_api.md, 5j): a pre forward is the before side, a post forward the after side, and FMRES_SUPERCEDE blocks a blockable event. An event with nothing to change or block (FM_PlayerPreThink, FM_StartFrame) runs pre forwards on its after side. forward_return has no value to set: hiding an entity in FM_AddToFullPack is returning FMRES_SUPERCEDE.
No equivalent: get_pdata_*/set_pdata_* and get_ent_data* (numeric offsets: read the member by name, Entity:get("m_iTeam")), fake_touch, call_think, attach_view, set_view, get_keyvalue, and the forwards FM_SetModel, FM_TraceLine, FM_TraceHull, FM_UpdateClientData, FM_KeyValue, FM_GetGameDescription, FM_ClientKill (each error names the replacement).
hamsandwich
RegisterHam(Ham_*, class, fn, post) (also RegisterHamPlayer, RegisterHamFromEntity), DisableHamForward, EnableHamForward, IsHamValid, SetHamParamInteger/Float/Vector/Entity/String, ExecuteHam, ExecuteHamB.
| Ham | Event | Writable parameters |
|---|---|---|
Ham_Spawn | player_spawn / entity_spawn | |
Ham_Think, Ham_Touch, Ham_Blocked, Ham_Use | think, touch, blocked, use | |
Ham_TakeDamage | player_damage / entity_damage | 4 damage, 5 damage type (not for players) |
Ham_TraceAttack (players) | player_trace_attack | 3 damage; the trace handle gives TR_iHitgroup |
Ham_Killed | player_killed / entity_killed | |
Ham_Player_PreThink, PostThink, Jump, Duck | player_pre_think, player_post_think, player_jump, player_duck | |
Ham_AddPlayerItem (player), Ham_Item_AddToPlayer (weapon) | player_pickup | |
Ham_Item_Deploy, Ham_Item_Holster | weapon_deploy, weapon_holster | |
Ham_Weapon_PrimaryAttack, SecondaryAttack, Reload, WeaponIdle | weapon_attack, weapon_reload, weapon_idle |
HAM_SUPERCEDE blocks the call (before side). ExecuteHam and ExecuteHamB both go through the hooks: Ham_Spawn, Ham_TakeDamage, Ham_Killed, Ham_Use, Ham_CS_RoundRespawn, Ham_Respawn, Ham_Item_PreFrame and Ham_CS_Player_ResetMaxSpeed (the speed reset), Ham_IsPlayer. The hooks have no return value, so GetHamReturn* and SetHamReturn* raise an error.
cstrike and fun
Functions that read or write members of the game's classes (armor type, kits, night vision, VIP, ammunition, silencers) need permissions = ["raw_properties"].
| Area | Functions |
|---|---|
| Money and score | cs_get/set_user_money, cs_get/set_user_deaths, set_user_frags, cs_set_user_hostagekills |
| Teams | cs_get_user_team (team, model number), cs_set_user_team |
| Equipment | cs_get/set_user_armor (amount, CS_ARMOR_*), cs_get/set_user_defuse, cs_get/set_user_nvg, cs_get/set_user_vip, cs_get_user_hasprim, cs_get_user_shield, give_item, strip_user_weapons |
| Ammunition and weapons | cs_get/set_user_bpammo, cs_get/set_weapon_ammo, cs_get_weapon_id, cs_get/set_weapon_silen, cs_get/set_weapon_burst, cs_get_user_weapon_entity, cs_get_item_id, cs_get_translated_item_alias |
| Look | cs_get/set_user_model, cs_reset_user_model, cs_get/set_user_zoom, set_user_rendering, get_user_rendering |
| Places | cs_get_user_buyzone, cs_get_user_mapzones (the buy zone only), set_user_origin, cs_user_spawn |
| Hostages and bomb | cs_get/set_hostage_foll, cs_get_hostage_id, cs_get/set_c4_explode_time, cs_get_c4_defusing |
| fun | get/set_user_godmode, set_user_health (0 kills), set_user_armor, get/set_user_maxspeed, get/set_user_gravity, get/set_user_noclip, get/set_user_footsteps, get/set_user_hitzones, get/set_client_listen, spawn |
Notes: cs_set_user_team between T and CT keeps the player alive with the items, as the game's own team swap (Player:switch_team); to or from spectators it goes through the team menu's rules (Player:join_team). cs_get_user_buyzone is true where the player may buy now (the zone and the buy time). No equivalent (each error names the replacement): cs_get_user_driving, cs_get_user_stationary, cs_get_user_plant, cs_get/set_user_tked, cs_get/set_no_knives, cs_set_ent_class, cs_get_weapon_info, cs_get/set_armoury_type, cs_get/set_user_lastactivity, cs_get/set_user_submodel.
ReAPI
| Area | Functions |
|---|---|
| Members and variables | get_member, set_member (members by the game's names: m_iTeam; arrays from element 0), get_member_game, set_member_game, get_entvar, set_entvar (var_*) |
| Players | rg_set_user_team, rg_switch_team, rg_swap_all_players, rg_add_account (AS_ADD, AS_SET), rg_give_item (GT_APPEND, GT_REPLACE, GT_DROP_AND_REPLACE), rg_remove_item, rg_remove_all_items, rg_drop_item, rg_drop_items_by_slot, rg_remove_items_by_slot, rg_has_item_by_name, rg_get/set_user_bpammo, rg_get/set_user_armor, rg_set_user_model, rg_reset_user_model, rg_give_defusekit, rg_round_respawn, rg_reset_maxspeed, rg_find_ent_by_class |
| Rounds | rg_round_end (WINSTATUS_*, ROUND_*), rg_update_teamscores, rg_restart_round |
| Hook chains | RegisterHookChain, DisableHookChain, EnableHookChain, SetHookChainArg, SetHookChainReturn (nothing to set: blocking is HC_SUPERCEDE), IsReapiHookOriginalWasCalled |
| Entities | is_entity, get_member_s, set_member_s (only on a valid entity), rg_create_entity, rg_remove_entity, rg_find_ent_by_owner, SetTouch, SetUse, SetThink (the entity's own callback replaced; "" puts the game's back) |
| More players | rg_join_team, rg_switch_weapon, rg_send_audio, rh_emit_sound2 |
| Movement | get_pmove (pm_origin, pm_velocity, pm_basevelocity, pm_angles, pm_flags, pm_onground, pm_waterlevel, pm_movetype, pm_bInDuck, pm_oldbuttons, pm_maxspeed, pm_player_index, pm_cmd, pm_frametime) and get_ucmd (ucmd_*) in RG_PM_Move handlers; get_movevar |
| Hook chain | Event | Writable arguments |
|---|---|---|
RG_CBasePlayer_Spawn, RG_CSGameRules_PlayerSpawn | player_spawn | |
RG_CBasePlayer_TakeDamage | player_damage | 4 damage |
RG_CBasePlayer_TraceAttack | player_trace_attack | 3 damage |
RG_CBasePlayer_Killed, RG_CSGameRules_PlayerKilled | player_killed | |
RG_CBasePlayer_PreThink, PostThink, Jump, Duck | player_pre_think, player_post_think, player_jump, player_duck | |
RG_PM_Move | player_move (pre handlers read the state before the move, post ones after it) | |
RG_PM_Jump | player_jump | |
RG_CBasePlayer_AddAccount | player_money | 2 amount |
RG_CBasePlayer_GiveDefaultItems | player_equip | |
RG_CBasePlayer_DropPlayerItem, RG_CBasePlayer_AddPlayerItem | player_drop, player_pickup | |
RG_CBasePlayer_SetClientUserInfoName | player_name | 3 name |
RG_HandleMenu_ChooseTeam | player_choose_team | 2 team (menu slot) |
RG_CBasePlayer_Radio | player_radio | |
RG_BuyWeaponByWeaponID, RG_BuyItem | player_buy | |
RG_RoundEnd | round_end | 2 event (reason), 3 delay |
RG_CSGameRules_RestartRound, OnRoundFreezeEnd, CheckWinConditions | round_start, freeze_end, team_win_check | |
RG_CGrenade_DefuseBombStart, DefuseBombEnd | bomb_defuse, bomb_defuse_end | |
RG_CGrenade_ExplodeBomb, ExplodeHeGrenade, ExplodeFlashbang, ExplodeSmokeGrenade | grenade_detonate | |
RG_ThrowHeGrenade, RG_ThrowFlashbang, RG_ThrowSmokeGrenade | grenade_thrown | |
RG_PlantBomb | bomb_planted | |
RG_CBasePlayerWeapon_DefaultDeploy, DefaultReload | weapon_deploy, weapon_reload | |
RG_CBasePlayer_Observer_SetMode | player_spectate |
HC_SUPERCEDE and HC_BREAK block the call (before side); HC_BREAK and HC_BYPASS also skip the later handlers. GetHookChainReturn raises an error (the hooks have no return value). The move itself cannot be changed (set_pmove, set_movevar): the server alone would break the client's prediction; Player:set_movement changes it for both. No equivalent: RG_PM_AirMove (movement settings, Player:set_movement; a slide fix that keeps players from stopping on a ramp's seams is its ramp_fix), RG_CBasePlayer_HasRestrictItem (block player_buy or player_pickup), RG_CSGameRules_FPlayerCanTakeDamage (block player_damage), and the others the errors name; rg_internal_cmd, rg_set_animation, rg_give_custom_item, rg_get/set_account_rules, rg_check_win_conditions; and elsewhere get_kvd/set_kvd (Entity:key_value), get_cd/set_cd, set_speak (Player:mute_voice), query_client_cvar, geoip_*.
Data: nvault, sqlx, json, EasyHttp
-
nvault on
cs.store(nvault_<name>.storein the plugin's data folder):nvault_open,nvault_close,nvault_set,nvault_pset(permanent),nvault_get(the value as a string,""when missing: Pawn's number form isstr_to_numof it),nvault_lookup(found, value, time stamp),nvault_touch,nvault_remove,nvault_prune,nvault_util_count. -
sqlx on
cs.database: SQLite,<db>.dbin the plugin's data folder (the tuple's database name; host, user and password are not used). For MySQL or PostgreSQL use a native module (samples/native/sql).SQL_MakeDbTuple,SQL_MakeStdTuple,SQL_SetAffinity("sqlite"),SQL_Connect(connection, error code, error),SQL_PrepareQuery(with format arguments),SQL_Execute(waits for the result: inplugin_initor at a map's start, not every frame),SQL_ThreadQuery(on the I/O thread; the handler runs on a later frame),SQL_QueryError,SQL_NumResults,SQL_MoreResults,SQL_NextRow,SQL_Rewind,SQL_ReadResult(columns from 0, or by name),SQL_IsNull,SQL_NumColumns,SQL_FieldNumToName,SQL_FieldNameToNum,SQL_AffectedRows,SQL_GetInsertId,SQL_GetQueryString,SQL_QuoteString,SQL_QuoteStringFmt,SQL_FreeHandle. -
json (values by handle; objects keep their keys' order):
json_parse(text or file, comments optional),json_serial_to_string,json_serial_size,json_serial_to_file,json_get_type,json_init_object/array/string/number/real/bool/null,json_deep_copy,json_free,json_equals,json_get_string/number/real/bool,json_array_get_count/value/string/number/real/bool,json_array_replace_*,json_array_append_*,json_array_remove,json_array_clear,json_object_get_count/name/value_at,json_object_get_value/string/number/real/boolandjson_object_set_*(names with dots reach inside withdot_not),json_object_has_value,json_object_remove,json_object_clear. -
EasyHttp (a part) on
cs.http(the hosts must be in the manifest'shosts):ezhttp_get/post/put/patch/delete(url, callback, options),ezhttp_create_options,ezhttp_destroy_options,ezhttp_option_set_header/body/timeout/user_data/url_parameter; in the callback (request, user data):ezhttp_get_http_code,ezhttp_get_data,ezhttp_get_error_code,ezhttp_get_error_message,ezhttp_get_headers.
Messages and log events
Messages are named, not numbered: get_user_msgid("TextMsg") gives the name back and every function takes it (SVC_TEMPENTITY is TempEntity). A plugin that hard-codes message numbers must use the names.
-
Sending (needs
permissions = ["raw_messages"]):message_begin(MSG_BROADCAST,MSG_ONE,MSG_ALL,MSG_PVS,MSG_PAS,MSG_PVS_R,MSG_PAS_R,MSG_ONE_UNRELIABLE),write_byte/char/short/long/angle/ coord/entity/string(and the_fforms),message_end, theemessage_*forms. It iscs.send_message(name, {{kind, value}...}, {dest, player, origin}): a message of a fixed size must fill it, and it passes through the other plugins'client_messagehandlers.MSG_INITandMSG_SPEChave no equivalent. For the HUD, the typed API is usually shorter:cs.chat,cs.center,cs.hud_message,cs.dhud_message,cs.hud_text(any size, no channels),cs.notify,Player:fade,cs.beam,cs.dynamic_light. -
Changing the game's messages:
register_message(name, fn)(fn(name, dest, entity) before it goes out;PLUGIN_HANDLEDblocks it),unregister_message,get_msg_args,get_msg_argtype(ARG_*),get_msg_arg_int/float/string,set_msg_arg_int/float/string,get_msg_origin,set_msg_block/get_msg_block(BLOCK_NOT,BLOCK_ONCE,BLOCK_SET). -
Events:
register_event(name, fn, flags, conditions...)runs fn(receiver) after the message went out (receiver 0 for a message to everyone); flagsato everyone,bto one player,ddead,ealive,fhumans,gbots; conditions"2=TERRORIST","2!x","2&part","1>0","1<5".register_event_ex(RegisterEvent_*flags),enable_event,disable_event,read_data,read_datanum,read_datatype. -
Log events: there is no log stream to read;
register_logevent(fn, argc, conditions...)gets the lines the game would log, made from the typed events, split as AMXX splits them (from 0:"Name<uid><id><TEAM>","triggered","Round_Start"):World triggered "Round_Start","Round_End","Game_Commencing","Restart_Round_(1_second)";Team "CT" triggered "CTs_Win" (CT "3") (T "1")and the other round ends; a player triggered"Planted_The_Bomb","Begin_Bomb_Defuse_With_Kit","Begin_Bomb_Defuse_Without_Kit","Defused_The_Bomb","Got_The_Bomb","Dropped_The_Bomb","Touched_A_Hostage","Rescued_A_Hostage","Killed_A_Hostage";joined team,killed ... with,committed suicide with,say,say_team,entered the game,disconnected.read_logargc,read_logargv,read_logdata,parse_loguser.
Not covered
Modules that patch the server's memory or call its functions by signature (Orpheu, Okapi, RAGE, get_pdata_* by offset) have no equivalent: the game's state is reached by name (Entity:get, the field table) and its behaviour through the events. A function compat/amxx does not have is nil (calling it says which name); cs_port lists them per plugin.
cs_port: translating the source
cs_port.py translates a plugin's Pawn source into a Classic Strike plugin on compat/amxx. It comes in the server and tools package (the dedicated server and the authors' tools, apart from the game), in data/plugin_sdk/cs_port/ (Python 3.10 or newer; tools/cs_port/ in the game's source):
python3 data/plugin_sdk/cs_port/cs_port.py scripting/myplugin.sma -I scripting/include -o myplugin --check
--check compiles what it wrote (with the package's cs_plugin check).
-
Input: the
.smaand the include folders it needs (-I, repeatable;include/next to the source is tried on its own). AMX Mod X's own includes (amxmodx, fakemeta, ReAPI, ...) are read for their declarations and never translated:compat/amxxgives those functions. The plugin's own includes are translated with it. -
Output: a plugin folder:
plugin.toml(with the permissions the calls need,raw_properties,raw_messagesandserver_consoleforserver_cmdand setting cvars),main.luau, and for a big plugin one module per source file sharing a tableM(Luau allows 200 locals per function);lang/<language>.tomlfrom the dictionaries it registers (--langnames AMX Mod X'sdata/langfolder,data/langnext to the scripting folder is tried on its own); andPORT.md. -
PORT.md lists what needs a hand:
TODO(port)lines (also in the code), the functionscompat/amxxlacks (the calls stay asamxx.name(...)and fail when they run), those without an equivalent, and what the plugin uses. -
**
--check** compiles every Luau file withnative/build/cs_luau_check.
What it translates, and how:
| Pawn | Luau |
|---|---|
#include, #define (with %1 patterns, name[%1], pasting), #if/#elseif | Done before parsing; a constant #define keeps its name |
cells, Float:, bool: | numbers and booleans; conditions on cells become ~= 0 |
a / b, a % b on integers | P.div, P.mod (truncated toward 0, as Pawn) |
&, \|, ^, ~, <<, >>, >>> | P.band ... P.ushr (32 bits, signed) |
| character arrays | strings: s[i] is P.ch(s, i), s[i] = c is P.setch, s[0] = EOS is s = "" |
Float:v[3] (and number arrays compat fills with vectors) | vectors: v[0] is v.x |
| other arrays | tables indexed from 0 (P.array({33, 32}, "")); assignment copies |
enum with sized fields (g_data[33][PlayerData]) | a table per element keyed by the fields |
switch (ranges, lists) | if/elseif |
for (new i = a; i < b; i++) | for i = a, b - 1 when the body leaves i and b alone; else while |
assignments and ++ inside expressions | done before the statement (in a function where it must stay conditional) |
out-parameters (get_user_name(id, name, len), &ref, arrays a stock writes) | results: name = amxx.get_user_name(id); a stock returns its value and then its outputs |
formatex(buf[len], ...) | buf = string.sub(buf, 1, len) .. text |
stock | only when called (Pawn compiles only those) |
..., numargs, getarg, vformat | Luau's ... |
static locals | a variable outside the function |
goto | TODO(port) and P.todo() (Luau has no goto) |
Which arrays hold text is not written in Pawn; it is found from use: string literals, the natives' string parameters, %s in format strings, characters written into them, and the arrays they are passed to or copied from. An array nothing tells apart is numbers, unless its name says text (szName, name, msg, ...).
What differs from Pawn:
-
Strings have no buffer. A copy or format into
buf[32]keeps the whole text; only a length under 32 or a literal longer than its length is cut (copy(s, 3, "abcdef")gives"abc"). - Integers are Luau numbers (doubles): exact to 2^53; overflow past 32 bits does not wrap except in the bit operations.
-
**
Float:casts of cells** (Float:fr[R_F_VELOCITY]) read the value as it is: what a plugin stores in an array is kept as a number, never as its bits.
compat/pawn (data/plugin_sdk/compat/pawn.luau) holds those helpers.
tools/cs_port/tests/run.sh checks the translator: tests/*.sma against tests/expected/ (--update after a deliberate change), every output and the compat libraries through cs_luau_check, and the translated plugins on a dedicated server: lang (each Pawn construct), game (the usual ways with players, hook chains and userinfo, with bots), data (celltrie, cellarray, files, floats, xs, forwards, callfunc) and natives_lib with natives_use (natives, callfunc and forwards between plugins). CS_PORT_EXTRA=.../plugin.sma also translates that plugin. tools/cs_port/dump_compat.sh rewrites compat_names.txt, the names compat/amxx exports, after it changes.
Testing a port
tools/plugin_compat_test.sh runs native/game/src/plugins/tests/compat (a plugin written as an AMXX port) with bots and a client that types commands and answers menus; it is a worked example of each function above.