본문으로 건너뛰기
cccskills
무료GitHub에 공개

add-lua-binding-api

Use this skill to expose Cataclysm-BN game functions and utilities to Lua. It guides you through organizing functions into libraries, registering constants and callbacks, documenting the API, and handling errors so Lua scripts can use the new bindings.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

원문원문 설명 보기

Add Cataclysm-BN Lua API bindings for global game functions, utility libraries, constants, callbacks, and domain-specific Lua namespaces.

cataclysmbn/Cataclysm-BN스타 1,289(GitHub 1,289 + cccskills 0)

실행 점수 미검증

설치 방법 보기

이럴 때 유용합니다

  • Expose game or map functions to Lua
  • Add constants or utility functions to a Lua library
  • Let Lua scripts register callbacks

포함된 파일(1)

  • SKILL.md10.3 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Add Lua API Bindings

This skill helps you expose global game functions and utilities to Lua through the game API.

API Organization

Lua API functions are organized into libraries (namespaces):

  • game.* - Game state, player access, time
  • map.* - Map operations, terrain, furniture
  • rng.* - Random number generation
  • gdebug.* - Debug functions
  • const.* - Game constants
  • Custom libraries for specific domains

Step-by-Step Process

1. Create or Extend Library Registration Function

In appropriate src/catalua_bindings_*.cpp file:

auto cata::detail::reg_my_api( sol::state &lua ) -> void
{
    DOC( "My API - Description of what this API provides" );
    auto lib = luna::begin_lib( lua, "myapi" );

    // Add functions to the library
    luna::set_fx( lib, "function_name", &my_function );

    // Add constants
    luna::set( lib, "CONSTANT_NAME", CONSTANT_VALUE );

    luna::finalize_lib( lib );
}

2. Examples by Domain

Game State API

auto cata::detail::reg_game_api( sol::state &lua ) -> void
{
    DOC( "Game state and control functions" );
    auto lib = luna::begin_lib( lua, "game" );

    // Get player
    luna::set_fx( lib, "get_player",
        []() -> Character& { return get_player_character(); } // *NOPAD*
    );

    // Get avatar (more specific)
    luna::set_fx( lib, "get_avatar",
        []() -> avatar& { return get_avatar(); } // *NOPAD*
    );

    // Get current time
    luna::set_fx( lib, "get_time",
        []() -> time_point { return calendar::turn; }
    );

    // Advance time
    luna::set_fx( lib, "advance_time",
        []( const time_duration &dur ) { calendar::turn += dur; }
    );

    luna::finalize_lib( lib );
}

Map API

auto cata::detail::reg_map_api( sol::state &lua ) -> void
{
    DOC( "Map manipulation functions" );
    auto lib = luna::begin_lib( lua, "map" );

    // Get map reference
    luna::set_fx( lib, "get_map",
        []() -> map& { return get_map(); } // *NOPAD*
    );

    // Spawn item at location
    luna::set_fx( lib, "spawn_item",
        []( const tripoint &pos, const itype_id &id, int count ) {
            get_map().add_item_or_charges( pos, item( id, calendar::turn, count ) );
        }
    );

    luna::finalize_lib( lib );
}

RNG API

auto cata::detail::reg_rng_api( sol::state &lua ) -> void
{
    DOC( "Random number generation" );
    auto lib = luna::begin_lib( lua, "rng" );

    // Random integer in range
    DOC( "Returns random integer between min and max (inclusive)" );
    luna::set_fx( lib, "rng",
        []( int min, int max ) -> int { return rng( min, max ); }
    );

    // Random from list
    DOC( "Returns random element from table" );
    luna::set_fx( lib, "random_entry",
        []( sol::table tbl ) -> sol::object {
            if( tbl.empty() ) { return sol::nil; }
            auto idx = rng( 1, tbl.size() );
            return tbl[idx];
        }
    );

    // One in X chance
    luna::set_fx( lib, "one_in",
        []( int chance ) -> bool { return one_in( chance ); }
    );

    // X in Y chance
    luna::set_fx( lib, "x_in_y",
        []( int x, int y ) -> bool { return x_in_y( x, y ); }
    );

    luna::finalize_lib( lib );
}

UI/Output API

auto cata::detail::reg_ui_api( sol::state &lua ) -> void
{
    DOC( "User interface and message functions" );
    auto lib = luna::begin_lib( lua, "ui" );

    // Display message
    luna::set_fx( lib, "message",
        []( const std::string &msg ) { add_msg( msg ); }
    );

    // Display colored message
    luna::set_fx( lib, "message_colored",
        []( const std::string &color, const std::string &msg ) {
            auto col = color == "red" ? c_red :
                       color == "green" ? c_green :
                       color == "blue" ? c_blue : c_white;
            add_msg( col, msg );
        }
    );

    // Query yes/no
    luna::set_fx( lib, "query_yn",
        []( const std::string &msg ) -> bool { return query_yn( msg ); }
    );

    luna::finalize_lib( lib );
}

Constants API

auto cata::detail::reg_constants( sol::state &lua ) -> void
{
    DOC( "Various game constants" );
    auto lib = luna::begin_lib( lua, "const" );

    // Map size constants
    luna::set( lib, "OM_OMT_SIZE", OMAPX );
    luna::set( lib, "OM_SM_SIZE", OMAPX * 2 );
    luna::set( lib, "OM_MS_SIZE", OMAPX * 2 * SEEX );
    luna::set( lib, "OMT_SM_SIZE", 2 );
    luna::set( lib, "OMT_MS_SIZE", SEEX * 2 );
    luna::set( lib, "SM_MS_SIZE", SEEX );

    // Movement costs
    luna::set( lib, "MOVE_COST", 100 );
    luna::set( lib, "ATTACK_COST", 100 );

    // Turn duration
    luna::set( lib, "TURN_DURATION", 1_seconds );

    luna::finalize_lib( lib );
}

3. Register in Main Binding

In src/catalua_bindings.h:

namespace cata::detail {
    void reg_my_api( sol::state &lua );
}

In src/catalua_bindings.cpp in reg_all_bindings():

reg_my_api( lua );

Advanced Patterns

Variadic Message Functions

// Accept variable arguments like print()
luna::set_fx( lib, "print",
    []( sol::variadic_args va ) {
        auto msg = cata::detail::fmt_lua_va( va );
        add_msg( msg );
    }
);

Tables as Parameters

// Accept Lua table, process as config
luna::set_fx( lib, "spawn_configured",
    []( const tripoint &pos, sol::table config ) {
        auto id = config.get_or<std::string>( "id", "" );
        auto count = config.get_or<int>( "count", 1 );
        auto active = config.get_or<bool>( "active", false );

        auto it = item( itype_id( id ), calendar::turn, count );
        if( active ) { it.activate(); }
        get_map().add_item( pos, it );
    }
);

-- Usage in Lua:
-- game.spawn_configured(pos, { id = "flashlight", count = 1, active = true })

Callback Registration

// Allow Lua to register callbacks
static sol::protected_function on_turn_callback;

luna::set_fx( lib, "register_on_turn",
    []( sol::protected_function func ) {
        on_turn_callback = func;
    }
);

// Later, in C++ game loop:
if( on_turn_callback ) {
    auto result = on_turn_callback();
    if( !result.valid() ) {
        sol::error err = result;
        debugmsg( "Lua callback error: %s", err.what() );
    }
}

Safe Function Calls with Error Handling

luna::set_fx( lib, "safe_execute",
    []( sol::state_view lua, const std::string &code ) -> bool {
        auto result = lua.safe_script( code );
        if( !result.valid() ) {
            auto err = sol::error( result );
            add_msg( c_red, "Lua error: %s", err.what() );
            return false;
        }
        return true;
    }
);

Logging API Pattern

auto cata::detail::reg_logging( sol::state &lua ) -> void
{
    auto lib = luna::begin_lib( lua, "log" );

    luna::set_fx( lib, "info", []( sol::variadic_args va ) {
        auto msg = cata::detail::fmt_lua_va( va );
        DebugLog( DL::Info, DC::Lua ) << msg;
        cata::get_lua_log_instance().add( cata::LuaLogLevel::Info, msg );
    });

    luna::set_fx( lib, "warn", []( sol::variadic_args va ) {
        auto msg = cata::detail::fmt_lua_va( va );
        DebugLog( DL::Warn, DC::Lua ) << msg;
        cata::get_lua_log_instance().add( cata::LuaLogLevel::Warn, msg );
    });

    luna::set_fx( lib, "error", []( sol::variadic_args va ) {
        auto msg = cata::detail::fmt_lua_va( va );
        DebugLog( DL::Error, DC::Lua ) << msg;
        cata::get_lua_log_instance().add( cata::LuaLogLevel::Error, msg );
    });

    luna::finalize_lib( lib );
}

Best Practices

1. Safety First

// Always validate parameters
luna::set_fx( lib, "spawn_monster",
    []( const tripoint &pos, const mtype_id &id ) {
        if( !id.is_valid() ) {
            debugmsg( "Invalid monster type: %s", id.c_str() );
            return;
        }
        g->place_critter_at( id, pos );
    }
);

// or as reference return with NOPAD
luna::set_fx( lib, "get_creature",
    []( const tripoint &pos ) -> creature& { // *NOPAD*
        return g->critter_at( pos );
    }
);

2. Use References for Performance

// Return reference, not copy (for large objects)
luna::set_fx( lib, "get_map",
    []() -> map& { return get_map(); } // *NOPAD*
);

3. Document Everything

DOC( "Spawns a monster at the given position" );
DOC_PARAMS(
    "pos: Tripoint - The position to spawn at",
    "id: MtypeId - The monster type to spawn",
    "returns: Monster - The spawned monster"
);
luna::set_fx( lib, "spawn_monster", &spawn_monster );

4. Consistent Naming

  • Use snake_case for function names (matching C++ convention)
  • Use UPPER_CASE for constants
  • Group related functions in libraries

5. Error Handling

luna::set_fx( lib, "risky_operation",
    []( int param ) {
        try {
            // risky code
        } catch( const std::exception &e ) {
            add_msg( c_red, "Error: %s", e.what() );
        }
    }
);

Note: Follow C++23 conventions from AGENTS.md: use auto, trailing return types, designated initializers, and std::ranges over for loops.

Testing Your API

-- In Lua console

-- Test function
local result = myapi.function_name(arg1, arg2)
print(result)

-- Test constant
print(const.CONSTANT_NAME)

-- Test with callbacks
myapi.register_callback(function()
    print("Callback triggered!")
end)

Common API Patterns

Getter/Setter Pattern

// Get value
luna::set_fx( lib, "get_difficulty",
    []() -> int { return get_option<int>( "DIFFICULTY" ); }
);

// Set value
luna::set_fx( lib, "set_difficulty",
    []( int value ) { get_options().get_option( "DIFFICULTY" ).set_value( value ); }
);

Builder Pattern

// Fluent API for complex object creation
luna::set_fx( lib, "create_item_builder",
    []( const itype_id &id ) -> item { return item( id, calendar::turn ); }
);

File Organization

  • catalua_bindings_game.cpp - Game state, player, time
  • catalua_bindings_map.cpp - Map operations
  • catalua_bindings_ui.cpp - UI and messages
  • Create new file for new API domain

References

  • Existing APIs: src/catalua_bindings_game.cpp
  • Utility functions: src/catalua_bindings.cpp
  • Luna library API: src/catalua_luna.h

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Expose complex C++ classes to Lua by adding bindings for methods, inheritance, constructors, properties, and operators. The skill also guides ownership handling and registration so Lua scripts can use the intended class interface.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Exposing a C++ class to Lua
  • Binding inherited class methods
  • Adding constructors and properties
cataclysmbn/Cataclysm-BN1.3천2026년 10월 27일 업데이트

Add Lua bindings that let Cataclysm-BN scripts access simple C++ types, including string IDs, enums, and basic read-only classes. The skill guides documentation macros, registration in the appropriate source file, and build and in-game checks.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Exposing a C++ string ID to Lua
  • Registering an enum for Lua scripts
  • Making a basic read-only C++ type available to Lua
cataclysmbn/Cataclysm-BN1.3천2026년 10월 27일 업데이트

Generate and synchronize player-facing changelog files across English, Korean, and Japanese from a Git reference range. It groups related changes, organizes featured updates and fixes, and preserves localized labels and relevant media.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Preparing changelogs between two Git refs
  • Updating English, Korean, and Japanese release notes
  • Grouping related player-facing changes
cataclysmbn/Cataclysm-BN1.3천2026년 10월 27일 업데이트

Create or update Deno and TypeScript scripts for Cataclysm-BN, following the project’s conventions. Use it for command-line tools, data migrations, code or documentation generators, Git hooks, and other development utilities.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Creating a Deno command-line utility
  • Writing a data migration script
  • Generating code or documentation
cataclysmbn/Cataclysm-BN1.3천2026년 10월 27일 업데이트

Use this skill when the same English text needs different translations in different parts of an application. It adds gettext context at the source, updates affected PO entries, and guides validation of translations and formatting checks for the touched locale.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Separate translations for an ambiguous label
  • Add context to translated JSON strings
  • Update and validate affected PO entries
cataclysmbn/Cataclysm-BN1.3천2026년 10월 27일 업데이트

A practical reference for adding Lua bindings to Cataclysm-BN. Look up Luna macros, usertypes, libraries, type and function patterns, documentation helpers, build steps, and common errors, with examples showing how C++ types and functions become usable from Lua.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Look up Luna macros for a type
  • Register C++ methods and properties for Lua
  • Troubleshoot binding or build errors
cataclysmbn/Cataclysm-BN1.3천2026년 10월 27일 업데이트

cataclysmbn의 스킬 모두 보기

이 스킬의 문제 신고