Examples/Server_and_client_working_together_a_shop_menu

Server.nut

RegisterRemoteFunc("shopBuy");

function shopBuy(player, item)                    // called by the client with CallServerFunc
{
    if (!player) return;
    if (item == 1 && player.Cash >= 200)
    {
        player.Cash = player.Cash - 200;
        player.SetWeapon(WEP_SHOTGUN, 50);
    }
    else if (item == 2 && player.Cash >= 100)
    {
        player.Cash = player.Cash - 100;
        player.Armour = 100.0;
    }
    CallClientFunc(player, "Main/Client.nut", "shopRefresh", player.Cash);
}

function onPlayerCommand(player, cmd, params)
{
    if (cmd == "shop") CallClientFunc(player, "Main/Client.nut", "shopOpen");
}

Client.nut

shopWin <- null;
cashLabel <- null;

function shopOpen()
{
    if (shopWin) { shopWin.Visible = true; ShowMouseCursor(true); return; }
    local x = ScreenWidth / 2 - 140, y = ScreenHeight / 2 - 90;
    shopWin = GUIWindow(VectorScreen(x, y), ScreenSize(280, 180), "Shop");
    shopWin.Moveable = true;
    cashLabel = GUILabel(VectorScreen(15, 30), ScreenSize(250, 20), "Cash: ?");
    local b1 = GUIButton(VectorScreen(15, 60), ScreenSize(250, 28), "Shotgun - $200");
    local b2 = GUIButton(VectorScreen(15, 95), ScreenSize(250, 28), "Armour - $100");
    local bc = GUIButton(VectorScreen(15, 135), ScreenSize(250, 28), "Close");
    b1.SetCallbackFunc("buyShotgun");
    b2.SetCallbackFunc("buyArmour");
    bc.SetCallbackFunc("shopClose");
    shopWin.AddChild(cashLabel);
    shopWin.AddChild(b1);
    shopWin.AddChild(b2);
    shopWin.AddChild(bc);
    AddGUILayer(shopWin);
    ShowMouseCursor(true);
}
function shopRefresh(cash) { if (cashLabel) cashLabel.Text = "Cash: $" + cash; }
function shopClose() { shopWin.Visible = false; ShowMouseCursor(false); }
function buyShotgun() { CallServerFunc("Main/Server.nut", "shopBuy", FindLocalPlayer(), 1); }
function buyArmour()  { CallServerFunc("Main/Server.nut", "shopBuy", FindLocalPlayer(), 2); }
NoteState that several handlers share is kept in global variables created with name <- value. They live in the root table, so they are shared between all server script files (or all client script files).
Categories: Worked examples