### Install Dependencies on Ubuntu Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx Installs required libraries for 'mongoc', 'protobuf', and general system dependencies on Ubuntu. ```bash apt-get install openssl apt-get install libssl-dev apt-get install -y libreadline-dev apt-get install autoconf apt-get install automake apt-get install libtool apt-get install libglu1-mesa-dev ``` -------------------------------- ### Linux/MacOS Package Installation Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx This snippet demonstrates how to make the package installation script executable and then run it on Linux or MacOS, specifying the build type for package selection. ```Bash # Linux/MacOS chmod +x ./install_pkgs.sh source ./install_pkgs.sh release # release与编译阶段的编译版本对应,即改脚本会使用相应的输出目录中的driver下载pkgs ``` -------------------------------- ### Windows Package Installation Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx This command executes the package installation script on Windows. ```Batch # Windows call install_pkgs.bat release ``` -------------------------------- ### Install Dependencies on CentOS Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx Installs essential libraries for 'mongoc' and 'protobuf' on CentOS, along with optional GUI packages. ```bash yum install -y openssl-devel yum install -y readline-devel yum install -y autoconf yum install -y automake yum install -y libtool yum install -y mesa-libGLU-devel yum groupinstall "GNOME Desktop" ``` -------------------------------- ### gs_py: Project Setup and Sample Usage Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Profiler/Gs_py_tool.md This example provides a practical walkthrough of setting up and using the gs_py project. It includes cloning the repository, initializing submodules, navigating to the sample directory, and executing a sequence of GDB commands with the gs.py script to analyze a coredump. ```bash git clone https://m68gitlab.g-bits.com/pkgs/gs_py.git cd gs_py git submodule update --init cd sample gdb gs core.22450 so gs.py ps true get_call_stacks 0x400055a9680 value_stack 0x400055a9680 get_all_handles "ojbect" get_obj_info 0x400060a63c0 get_obj_vars 0x400060a63c0 get_obj_var_info 0x400060a63c0 b box_value_print 0x4000608de00 value_print 0x40005381a10 ``` -------------------------------- ### Install Protobuf Dependencies on MacOS Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx Installs the necessary build dependencies for the 'protobuf' library on macOS using Homebrew. ```bash brew install autoconf brew install --build-from-source automake brew intsall libtool ``` -------------------------------- ### Execute Command on Windows Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx This snippet demonstrates how to execute a command or application on Windows, including passing arguments. The example uses a hypothetical 'test' command. ```batch test debug "/s 5 /D TEST_ROUND=1" ``` -------------------------------- ### Install Dependencies on Rocky Linux 9 Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx Installs necessary development libraries for 'mongoc', 'protobuf', and 'gs' on Rocky Linux 9 using the DNF package manager. ```bash dnf install openssl-devel dnf install readline-devel dnf install autoconf dnf install automake dnf install libtool dnf install zlib-devel dnf install gcc-c++ make cmake dnf install cmake ``` -------------------------------- ### Install Homebrew and CMake on MacOS Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx Installs Homebrew, a package manager for macOS, and then uses it to install CMake version 3.16 or higher from source. ```bash ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" brew install --build-from-source cmake ``` -------------------------------- ### Install Specific Package Source Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx Details the usage of 'install_pkg_source.sh' to download and build specific package sources or all packages, requiring a pre-compiled driver. ```bash ./install_pkg_source.sh $1 $2 $3 # $1 具体pkg名称 或 all(所有pkgs) # $2 已编译好的driver的版本: debug/release # $3 是否执行pkg的build批处理 ``` -------------------------------- ### GitLab CI/CD Pipeline Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx A basic .gitlab-ci.yml file defining two stages: 'build' and 'test'. The build stage checks the Ruby version and runs 'rake', while the test stages execute different 'rake test' commands. ```YML stages: - build - test build-code-job: stage: build script: - echo "Check the ruby version, then build some Ruby project files:" - ruby -v - rake test-code-job1: stage: test script: - echo "If the files are built successfully, test some files with one command:" - rake test1 test-code-job2: stage: test script: - echo "If the files are built successfully, test other files with a different command:" - rake test2 ``` -------------------------------- ### Module Load Static Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ObjectOrientation/Import.md Shows a practical example of module loading, where functions within an imported module are called after the module is statically loaded. Includes the content of the imported module 'example.gs' and the main script 'src.gs'. ```js // example.gs void create() { printf("example Instance.\n"); } public string func() { return "Helloworld"; } // src.gs import example; printf("Now test: %s\n" ,example); printf("%s\n", example.func()); // This is equivalent to // printf("%s\n", load_static(example, this_domain()).func()); printf("%s\n", example.func()); ``` -------------------------------- ### Execute Shell Script on Linux/MacOS Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx This snippet shows how to make a shell script executable and then run it on Linux or MacOS systems. It includes an example of passing arguments to the script. ```bash chmod +x ./test.sh ./test.sh debug "/s 5 /D TEST_ROUND=1" ``` -------------------------------- ### GS Domain Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ComplexTypes/Domain.mdx This C++ code snippet defines a simple integer variable 'i' and two public methods, 'test1' and 'test2', which increment and decrement 'i' respectively, printing the result. This serves as a basic example for demonstrating domain functionality. ```cpp int i = 0; public void test1() { i = i + 1; printf("i = %d\n", i); } public void test2() { i = i - 1; printf("i = %d\n", i); } ``` -------------------------------- ### Import Path Resolution Examples Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ObjectOrientation/Import.md Provides examples illustrating how GS resolves import paths, including omitting '.gs', using '.' for directory separation, and handling relative paths like current directory ('.') and parent directory ('..'). ```js import pkg.cjson.json; // Loads /pkg/cjson/cjson.gs ``` ```js import pkg.cjson; // Also loads /pkg/cjson/cjson.gs ``` ```js import pkg.cjson.*; // Loads all gs files in /pkg/cjson/ ``` ```js import .bar; // Loads bar.gs in the current script's directory ``` ```js import ..bar; // Loads bar.gs in the parent directory of the current script ``` -------------------------------- ### C++ Socket Client/Server Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ComplexTypes/Socket.mdx 这是一个使用gs_doc库创建TCP客户端和服务器的C++示例。客户端连接到指定端口,接收数据直到连接关闭。服务器监听端口,接受连接,并向客户端发送N次数据。最后,服务器打印接收到的数据总大小和数值总和。 ```C++ const int PORT = 4678; int size = 0; int sum = 0; handle sem_id = sync_object.create_semaphore(); // Connect to server & receve data until peer closed void start_client() { handle fd = socket.create(); fd.connect("127.0.0.1", PORT); for (;;) { let int ret, buffer buf = fd.recv(1024); if (ret <= 0) break; size += ret; for (int i = 0 upto buf.length() - 1) if (buf[i] >= '0' && buf[i] <= '9') sum += buf[i]; } fd.close(); sem_id.give(); } string data = __FILE__ + "1234567890"; data = data + data + data + data + data; data = data + data; const int N = 3000; void start_server() { handle sfd = socket.create(); sfd.set_opt(SockOptLevel.SOCKET, SockOpt.REUSEADDR, 1); sfd.bind(SockParam.INADDR_ANY, PORT); sfd.listen(64); // Send N times to single client let handle cfd, int ip = sfd.accept(); for(int i = 1 upto N) cfd.send(data); cfd.close(); sem_id.take(); printf("sum = %d,",sum); printf("size = %d\n", size); } void test() { coroutine.create(0, "start_server"); coroutine.create(0, "start_client"); } test(); ``` -------------------------------- ### Program API: Get Components Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ComplexTypes/Program.mdx Retrieves all components included in the program. ```javascript array comps = program.get_components(); ``` -------------------------------- ### Enum Usage Example (JavaScript) Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Constants.mdx Provides a practical example of using enums in JavaScript, assigning values and demonstrating a comparison. It outlines the resulting value-to-constant mapping. ```js enum State { IDLE = 10, RUN, WAIT = 35, EAT, DRINK, }; bool falg = (State.IDLE == 10); // flag = true ``` -------------------------------- ### Gs Defer: Resource Management Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Control/Defer.mdx An example demonstrating the practical use of 'defer' in Gs for resource management, specifically closing a queue after a function completes its operations. ```cpp public mixed send_request_directly(object conn, map args) { queue q = queue.create("", 1); defer q.close(); // 离开函数后关闭队列 ... mixed result = q.receive(10); return result; } ``` -------------------------------- ### 启动gs.exe驱动程序 Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Quick_start_guide.md 使用`--help`参数启动gs.exe可以查看所有可用的启动参数。此命令是了解和配置驱动程序启动选项的基础。 ```bash gs.exe --help ``` -------------------------------- ### Get Range from Buffer Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Variables/Variables_string_buffer.mdx Extracts a sub-buffer from a specified position and length. The example gets 3 characters starting from index 6. ```Go export const buffer_apis = [ { "id": 6, "proto": "buffer buffer_instance.get_range(int pos, int count = -1)", "desc": "取子buffer", "usage": "buffer buf = (buffer)"hello world"; buffer child = buf.get_range(6,3); // child = "wor"" } ``` -------------------------------- ### gs_doc: Configuration Parameters for Startup Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Quick_start_guide.md This snippet outlines the configuration parameters for the gs_doc application, which are typically passed as command-line arguments prefixed with '--'. These configurations manage advanced features like memory allocation, threading, JIT compilation, garbage collection, and system command execution. ```Shell Configuration: --bin-alloc Use binary allocator. --call-stack-size %d Set the depth of function call context. --enable-threads If 0, disable threads other than parallel scheduler and main thread, prohibit socket daemons and new thread creation; usually used with /s 0. --enable-color-error Set error output messages to red. --enable-compiler-debug Enable compiler debugging, display generated assembly code. --enable-debugger [%d]::[%d] Allow embedded debugger to work, optional debugger port and state (1 for random port, 1 or 0 for pause on startup). --enable-gc-log Enable GC log. --enable-jit [0|1|2] Enable JIT (0 for disable, 1 for asmjit, 2 for llvmjit). --enable-jit-debug Enable JIT debugging. --enable-jit-log Enable JIT logging. --enable-multi-cpu Use multi-CPU (may cause performance degradation). --enable-system-command Enable efun "system" (security risk). --enable-coverage Enable coverage statistics. --gc-count-upper-bound Set allocation size count upper bound, 0 for no limit. --gc changedset Use change set for minor GC marking. --gc cardtable Use card table for minor GC marking. --gc changedset+cardtable Use both change set and card table for minor GC marking. --gc full Use only full GC, no minor GC. --gc-force-full-gc Enable forced full GC. --gc-lms-cached Set the size of deleted pages cached by each LMS when releasing memory pages (bytes). --gc-global-cached Set the size of deleted pages cached by all LMS when releasing memory pages (bytes). --gc-gray-page-size Set the number of cells in a gray page (0 for no gray pages). --gc-max-dynamic-work-us Set the maximum working time for dynamic worker threads (microseconds). --gc-max-dynamic-worker Set the maximum number of dynamic worker threads. --gc-max-ub-pool Set the maximum number of cell/block pools. --gc-min-gc-interval Set the minimum time for GC interval (milliseconds). --gc-quota-to-full-gc Hint for full GC (when old cell size exceeds limit). --gc-quota-to-minor-gc Hint for minor GC (when new cell size exceeds limit). --gc-max-quota-to-minor-gc Limit minor GC (when new cell size exceeds limit). --gc-stat-recycle Print recycle information after specified rounds for debugging. --gc-time-to-long-live Set the default long-lived time for GC referenced values. --gc-thread-threshold Limit dynamic worker threads (when GC allocation size exceeds limit). --ignore-inexist-import Do not report compilation errors when import files are missing. --jit-mem-size Set JIT memory pool reserved size (MB, default: 1024). ``` -------------------------------- ### Handle Initialization Examples Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Variables/Variables_handle.mdx Demonstrates how to create and initialize handles for various resource types like sockets, domains, timers, coroutines, share values, sync objects, and files. ```C++ handle h1 = socket.create(); // socket handle h2 = domain.create(); // domain handle h3 = timer.create(0.1, 0, (: not_execute_me :)); // timer handle h4 = this_coroutine(); // coroutine handle h5 = socket.create(); // socket handle h6 = share_value.allocate("unamed", 0); // share_value handle h7 = sync_object.create_semaphore(); // sync_object handle h8 = file.open("cn_gbk.txt", "r", file_data); // file ``` -------------------------------- ### gs_doc: Command-Line Options for Startup Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Quick_start_guide.md This snippet details the command-line options available for starting the gs_doc application. These options control various functionalities such as enabling the command line interface, debugging, logging, and network port configurations. ```Shell Usage: gs_doc [OPTION]... [FILE]... Options: -c1 Enable command line. -c2 Enable command line and allow input before startup is complete. -d[port] Enable debugger on specified port. -e[q] Set the virtual machine's startup script (if 'q' is set, exit after completion). -l filename Set the log file name. -o script Set the base script (executed before the startup script). -p port Set the Telnet port. -r directory Set the virtual machine root directory. -s size Set the default thread pool size. -sm count Set the GC static worker thread count. -w password Set the Telnet password. -wd directory Set the working directory. -D definition Declare a definition. -v Print version information. ``` -------------------------------- ### Example Usage of Object Methods Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ComplexTypes/Object.mdx Demonstrates the usage of object methods like `show_count`, `add_count`, and `wait_post_finish` in a practical scenario. It shows how to load a static object and call its methods sequentially. ```gs object obj = load_static("/obj.gs", this_domain()); @obj.show_count(); @obj.add_count(); obj.wait_post_finish(); write("program finish\n"); ``` -------------------------------- ### HelloWorld示例输出 Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Structure_of_a_program.mdx 展示了运行HelloWorld示例时在控制台的预期输出。 ```bash helloworld create helloworld ``` -------------------------------- ### Get Value at Buffer Position Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Variables/Variables_string_buffer.mdx Retrieves the value at a specific position within the buffer. The example gets the ASCII value of the character at index 1. ```Go export const buffer_apis = [ { "id": 5, "proto": "mixed buffer_instance.get(int pos)", "desc": "取值", "usage": "buffer buf = (buffer)"hello world"; mixed val = buf.get(1); // val = 101 ('e'的ASCII)" } ``` -------------------------------- ### Build using build_all Script (Linux) Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx Explains how to use the 'build_all.sh' script in the 'build' directory to compile all project dependencies, optionally downloading source code. ```bash cd build ./build_all.sh $1 $2 # $1 编译类型: debug/release等 # $2 是否下载所有pkg源码并编译 # 1. 下载并编译(原pkgs中的各pkg会替换为源码中src的软链接) # 2. 不下载,等效于上文中cicd的build_cmake+install_pkgs ``` -------------------------------- ### Delete Data from Buffer Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Variables/Variables_string_buffer.mdx Deletes a specified number of elements from a buffer starting at a given position. The example shows deleting 4 characters starting from index 1. ```Go export const buffer_apis = [ { "id": 3, "proto": "void buffer_instance.delete_at(int pos, int num = 1)", "desc": "删除", "usage": "buffer buf = buffer.allocate(0); buf << "hello world"; buf.delete_at(1,4); // buf = "h world"" } ``` -------------------------------- ### Get Map Value by Index Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Variables/Variables_array_map.mdx Retrieves the value at a specific index based on the map's iteration order. An exception is thrown if the index is out of bounds. The example gets the value at index 0. ```mixed map m = {"a": 2, "b": 3}; int val = m.get_val_at(0); ``` -------------------------------- ### Get Map Key by Index Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Variables/Variables_array_map.mdx Retrieves the key at a specific index based on the map's iteration order. An exception is thrown if the index is out of bounds. The example gets the key at index 0. ```mixed map m = {"a": 2, "b": 3}; string key = m.get_key_at(0); ``` -------------------------------- ### 使用启动参数启动驱动程序 Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Quick_start_guide.md 这是一个示例批处理脚本,演示了如何使用多个启动参数来配置gs.exe驱动程序。它设置了根目录、执行启动脚本、预加载脚本以及挂载目录。 ```powershell .\bin\gs.exe /r ./server/ /e /server.gs /m /preload.gsh --mount ./etc::/etc_m ``` -------------------------------- ### Compile and install GCC on CentOS Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx These commands compile and install GCC 5.5.0 on CentOS. It's recommended to check if g++ is available before running 'make' and to specify the job number for 'make' to control compilation speed. ```bash # make前检查g++是否可用,若无g++,则 yum install gcc-c++ # make -j [number] 指定编译job number,job number 为 1 时会很慢 make make install ``` -------------------------------- ### CMakeLists.txt for GSBind Sample Project Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Plugins/Doc_plugin_gsbind.md This CMakeLists.txt file configures the build process for the GSBind sample project. It sets the C++ standard, defines library output names based on the operating system, and includes necessary directories for GSBind headers. ```cmake cmake_minimum_required(VERSION 3.16) project(gsbind_sample) set(CMAKE_CXX_STANDARD 14) if (WIN32) set(SUFFIX_NAME "dll") elseif (APPLE) set(SUFFIX_NAME "dylib") else () set(SUFFIX_NAME "so") endif() include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/gsbind) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/src DIR_SRCS) add_library(${PROJECT_NAME} SHARED ${DIR_SRCS}) set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "") ``` -------------------------------- ### Download and install CMake on CentOS Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx This bash script downloads and installs a specific version of CMake (3.17.2) on CentOS. It creates a directory, downloads the tarball, extracts it, and then creates a symbolic link to the CMake executable in the system's PATH. ```bash mkdir /opt/cmake wget https://cmake.org/files/v3.17/cmake-3.17.2-Linux-x86_64.tar.gz tar -zxf cmake-3.17.2-Linux-x86_64.tar.gz mkdir /usr/local/cmake mv ./cmake-3.17.2-Linux-x86_64 /usr/local/cmake sudo ln -s /usr/local/cmake/cmake-3.17.2-Linux-x86_64/bin/c* /usr/bin/ ``` -------------------------------- ### Building GS with Clang Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx This command demonstrates how to build the GS project using Clang, by passing 'clang' as an additional argument to the build script. ```Bash ./build_cmake.sh release 1 compiler clang ``` -------------------------------- ### HelloWorld示例 (GS) Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Structure_of_a_program.mdx 这是一个使用GS语言编写的HelloWorld示例,展示了对象的创建和销毁过程。它定义了`create`、`hello`和`destruct`函数,并演示了它们的调用顺序。 ```cpp void create() { write("create\n"); hello(); } void hello() { write("helloworld\n"); } void destruct() { write("destruct\n"); } hello(); ``` -------------------------------- ### boot.plist 示例 - set 和 run 指令 Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Plugins/Doc_plugin_archive.md 展示了boot.plist文件中set指令用于设置环境变量,以及run指令用于执行脚本文件的用法。 ```plaintext set some_env_var 1 run /main.gs ``` -------------------------------- ### Find Substring in Buffer Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Variables/Variables_string_buffer.mdx Searches for the first occurrence of a substring within a buffer and returns its starting index. The example finds 'wo' in 'hello world'. ```Go export const buffer_apis = [ { "id": 4, "proto": "int buffer_instance.find(mixed val)", "desc": "查找", "usage": "buffer buf = (buffer)"hello world"; int index = buf.find("wo"); // index = 6" } ``` -------------------------------- ### Component Script Naming (GS) Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/CodingGuidelines/Filename.md Component scripts are identified by starting with 'F' (for feature) followed by words in CamelCase. Examples are provided for component scripts within the engine0 framework. ```gs FEntity.gs FEntityContainer.gs FLookField.gs ``` -------------------------------- ### Build and Test using CICD Scripts (Linux) Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx Provides commands to build and test the project using shell scripts from the 'cicd' directory. Includes setting execute permissions and passing build parameters. ```bash cd cicd chmod +x ./build_cmake.sh ./build_cmake.sh $1 $2 # $1 参数为 debug / release # $2 表示是否完整编译三方库 # 如: ./build_cmake.sh release 1 cd cicd chmod +x ./install_pkgs.sh ./install_pkgs.sh $1 chmod +x ./test.sh ./test.sh $1 $2 # $1 参数为 debug / release # $2 为运行参数 如 "/s 5 /D TEST_ROUND=1" # ./test.sh release "/s 5 /D TEST_ROUND=1" ``` -------------------------------- ### Get Range of Elements Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Variables/Variables_array_map.mdx Extracts a sub-array (range) of elements from the original array, starting at a specified position and continuing for a given count. If count is -1, it extracts elements to the end of the array. ```Go export const array_apis = [ { "id": 8, "proto": "array array_instance.get_range(int pos, int count = -1)", "desc": "取子array", "usage": "array arr = [1, 2, nil, \"Three\", 2]; array child = arr.get_range(2,2); // child = [nil, \"Three\", 2]" } ``` -------------------------------- ### GS Script for Performance Benchmarking Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Plugins/Doc_plugin_gsbind.md This GS script benchmarks the performance of calling the 'add' function using both FFI and GSBind. It imports the GSBind sample and FFI modules, loads the dynamic library, and measures the time taken for a large number of function calls. ```gs // hello_gsbind.gs // Import gsbind sample import .gsbind_sample; // Import ffi sample import builtin.ffi.gsffi; const string dll = "/__dll/gsbind_samlpe.gs"; gsffi.load_library(dll, __DIR__ "gsbind_sample.ffi", this_domain(), this.name()); dll.add_dependent(this); void benchmark() { int start_time, end_time; for(int iter = 0 upto 3) { start_time = time.time_ms(); for(int i = 0 upto 10000000) { dll.add(1,2); } end_time = time.time_ms(); printf(HIC"FFI call add func(10M) time cost: %dms\n"NOR, end_time - start_time); } for(int iter = 0 upto 3) { start_time = time.time_ms(); for(int i = 0 upto 10000000) { gsbind_sample.add(1,2); } end_time = time.time_ms(); printf(HIC"Gsbind call add func(10M) time cost: %dms\n"NOR, end_time - start_time); } } benchmark(); ``` -------------------------------- ### Program API: Get Program Name Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ComplexTypes/Program.mdx Gets the name of the object managed by the program. ```javascript string obname = program.get_name(); ``` -------------------------------- ### Download GCC 5.5.0 prerequisites on CentOS Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Complication_guide.mdx This bash script downloads the necessary prerequisites for compiling GCC 5.5.0. It includes steps to create a directory, download the tarball, and extract it. It also modifies the download_prerequisites script to use HTTP instead of FTP. ```bash mkdir /opt/gcc cd /opt/gcc wget http://mirror.hust.edu.cn/gnu/gcc/gcc-5.5.0/gcc-5.5.0.tar.gz # wget http://ftp.gnu.org/gnu/gcc/gcc-5.5.0/gcc-5.5.0.tar.gz tar -zxf gcc-5.5.0.tar.gz cd gcc-5.5.0 ./contrib/download_prerequisites # 其中download_prerequisites文件中GCC依赖库的地址不对,需要进行以下更改 # 将ftp://gcc.gnu.org/pub/gcc/infrastructure/ 全部替换为 http://gcc.gnu.org/pub/gcc/infrastructure/ (这里一共是四个需要修改的) sed -i 's/ftp/http/g' ./contrib/download_prerequisites cd .. ``` -------------------------------- ### Get Share Value Size Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ComplexTypes/Share_value.mdx Returns the size of the share_value. Optionally accepts a path to get the size of a nested element. ```javascript { "id": 3, "proto": "int share_value_instance.length(handle id, array? path = nil)", "desc": "share_value大小", "usage": "int size = sv.length(); // size = 2" } ``` -------------------------------- ### Logical NOT Operator Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Operators.mdx Shows the logical NOT operator (!), which inverts the boolean value of its operand. This example demonstrates how '!0' results in 'true'. ```js bool flag = !0;// flag is true ``` -------------------------------- ### Bitwise NOT Operator Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Operators.mdx Demonstrates the bitwise NOT operator (~), which inverts each bit of an integer. The example shows the result of applying '~' to the integer 3. ```js int i = 3; printf("~i=%d",~i);// -4 ``` -------------------------------- ### gs Script for gsbind Map Construction Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Plugins/Doc_plugin_gsbind.md A gs script that imports the gsbind sample module and calls the `construct_map` function with sample data. The output demonstrates the created map, including string and buffer values. ```gs // test.gs import .gsbind_sample; write(gsbind_sample.construct_map(["aa", 11], ["bb", 22])); ``` -------------------------------- ### JavaScript Class Deserialization with __deserialize Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ComplexTypes/ClassMap.mdx This snippet demonstrates how to define and use a static __deserialize method within a class for handling deserialization. The example shows a class 'Example' with an 'a' field, a static __deserialize method that takes a map and returns an 'Example' instance, and how to serialize and deserialize an object using JSON functions. ```javascript class Example { int a = 1; public static Example __deserialize(map data) { Example ex = Example.new(); ex.a = data["a"]; // 从序列化数据中读取 a 的值 return ex; } } Example ex = Example.new(); string dat = json.save(ex); Example ex2 = json.load(dat); // 反序列化时调用 Example.__deserialize writeln(ex2); // 输出: // class Example{ /* sizeof() == 1 */ // "a" : 1, // } ``` -------------------------------- ### GS Object Lifecycle Management Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ComplexTypes/Object.mdx Demonstrates the lifecycle of a GS object, including loading, instantiation, and manual destruction. It shows how `load_static`, `new_object`, and `destruct_object` interact with the object's `create` and `destruct` methods. ```gs import .example; load_static(example, this_domain(), "load_static()"); new_object(example, this_domain(), "new_object()"); destruct_object(example); ``` -------------------------------- ### Logical AND Operator Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Operators.mdx Illustrates the logical AND operator (&&) which evaluates to true if both operands are true. This example shows its use in assigning a boolean value to a flag. ```js bool flag = 1 && 0;// flag is false ``` -------------------------------- ### Logical OR Operator Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Operators.mdx Demonstrates the logical OR operator (||), which evaluates to true if at least one of the operands is true. This example shows its application in setting a boolean flag. ```js bool flag = 1 || 0;// flag is true ``` -------------------------------- ### Loading a Library with FFI in gs Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Plugins/Doc_plugin_gsffi.md Demonstrates how to load a dynamic library using gsffi in a gs script. It explains the parameters for `gsffi.load_library`, including the virtual path, FFI file path, domain, and module name for structure declarations. ```gs gsffi.load_library(string name, string path, domain dom, string st_mod) ``` -------------------------------- ### Compound Assignment Operator Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Operators.mdx Provides examples of compound assignment operators like '+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '~=', '<<=', and '>>='. These operators combine an arithmetic or bitwise operation with assignment. ```js i += 4; // i = i + 4 j %= 2; // j = j % 2 ``` -------------------------------- ### Get Program Components, Variables, and Functions Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ComplexTypes/Program.mdx Obtains lists of components, variables, and functions that a program manages. These methods provide insights into the structure and capabilities of a program. ```cpp ent_program.get_components(); ent_program.get_object_vars(); ent_program.get_functions(); ``` -------------------------------- ### GSBind Sample FFI Definition Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Plugins/Doc_plugin_gsbind.md This file defines the interface for the 'gsbind_sample' module, specifying the 'add' function signature for FFI calls. This .ffi file is used when only GSBind is supported. ```cpp //gsbind_sample.ffi module(gsbind_sample) { int add(int i, int j); } ``` -------------------------------- ### C++: Domain Lock Example with try_lock Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ComplexTypes/Domain.mdx Provides an example of using `try_lock` in C++ for domain operations. The code within the `try_lock` block will cause an error if any cross-domain operations are performed. ```cpp void foo() { try_lock(this) { // 这中间任何跨域操作会报错 } } ``` -------------------------------- ### GS Object Script Layout Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/CodingGuidelines/ObjectScript.md Demonstrates the recommended layout for a GS object script, including preprocessor directives, component declarations, import statements, macro definitions, enums, constants, member variables, constructor, and destructor. ```C++ // 预处理 #pragma parallel #pragma disable_debug #pragma default_object #pragma export_macros #pragma export_imports // 组件 component engine.components.FEntity; component pkg.common_event.FCommonEvent; // import 列表 import engine.import; import engine.mods.net; import gs.bin.msgpack; import pkg.util_lib; // 宏定义 #define TRACE(...) #define TRACE_INFO(...) #define TRACE_WARN(...) // 枚举列表 enum ServerState { Unknown, Online, Offline, } // 常量 const int SCAN_INTERVAL = 60; const int MAX_COUNT = 100000; // 成员变量 readonly int _total_count := 0; readonly map _scan_obs := make_readonly({}); // 构造函数 void create() { } // 破坏函数 void destruct() { } ``` -------------------------------- ### Coroutine Local User Value Operations Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ComplexTypes/Coroutine.mdx Demonstrates the usage of `set_local_user_value`, `get_local_user_value`, and `remove_local_user_value` for managing local data within coroutines. It also includes an example of cross-domain access restrictions for these values. ```C++ public void test_local_user_value() { // 创建协程 coroutine co = coroutine.create(nil, () { // 在协程内设置本地用户值 this_coroutine().set_local_user_value("test_key", "test_value"); printf("Get value in coroutine: %O\n", this_coroutine().get_local_user_value("test_key")); }); // 主线程获取协程的本地用户值 co.wait(); printf("Get value in main thread: %O\n", co.get_local_user_value("test_key")); // 删除并检查 if (co.remove_local_user_value("test_key")) { printf("Delete success, get again: %O\n", co.get_local_user_value("test_key")); } // 跨域访问限制示例 domain d = domain.create(); coroutine co2 = coroutine.create_with_domain(nil, d, parallel () { // 设置非parallel的值 this_coroutine().set_local_user_value("normal_key", []); // 设置parallel的值 this_coroutine().set_local_user_value("parallel_key", make_parallel([])); }); co2.wait(); // 只能获取parallel的值 printf("Cross-domain get parallel value: %O\n", co2.get_local_user_value("parallel_key")); printf("Cross-domain get normal value: %O\n", co2.get_local_user_value("normal_key")); // Error } ``` -------------------------------- ### Coroutine Domain Mismatch Error Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ComplexTypes/Coroutine.mdx Illustrates an error scenario where a coroutine's execution domain differs from the domain of the function passed to it. This example uses `coroutine.create_with_domain` and shows how to check the function's argument domain. ```C++ public void test() { printf("current domain: %M\n", this_domain()); function fn = (: printf, "%O\n", { 1 : 2 } :); printf("function arg domain:%M\n", fn.get_arg_domain()); coroutine c = coroutine.create_with_domain(nil, domain.create(), fn); printf("entry domain: %M\n", c.get_entry_domain()); c.wait(); } ``` -------------------------------- ### Importing Plugins Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ObjectOrientation/Import.md Details how to import specific plugins in newer versions of GS, listing the plugins that have been separated from the core. Provides an example of importing the 'regex' plugin. ```js import gs.bin.regex; // import gs.bin.PLUGINS_NAME; regex.match("abc", "abc"); ``` -------------------------------- ### Create Handle Instance Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Basic/Variables/Variables_handle.mdx Demonstrates how to create a handle instance with a specified type. ```cpp handle hd = domain.create("hello"); ``` -------------------------------- ### 使用启动参数快速测试 Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Information/Quick_start_guide.md 通过设置根目录为当前目录并指定启动脚本,可以使用此命令快速启动驱动程序进行测试。 ```powershell gs.exe /r ./ /e /test.gs ``` -------------------------------- ### C++: Merged Domain Operations Example Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/ComplexTypes/Domain.mdx Demonstrates merged domain operations in C++ to ensure atomicity and prevent issues caused by object state changes between cross-domain calls. This example contrasts merged operations with unmerged ones, highlighting the reduction in failure rates. ```cpp #pragma parallel import gs.lang.*; import .d3; readonly int N := 10000; public void test() { test_one(); test_two(); } // 未合并域操作 public void test_one() { object ob = new_object(d3, domain.create()); sync_object sem = sync_object.create_semaphore(); // 其他协程等待域锁让出后执行 coroutine co1 = coroutine.create_in_thread("co1", domain.create(), (: co_entry_say, ob, sem :)); coroutine co2 = coroutine.create_in_thread("co2", domain.create(), (: co_entry_nogood, ob, sem :)); sem.take(); sem.take(); printf("case total say %d, failure times: %d\n", N, ob.get_failure_say_times()); ob.close(); sem.close(); } void co_entry_say(object ob, sync_object sem) { for (int i = 1 upto N) { // 未合并域操作 ob=>good(); catch(ob=>say()); coroutine.sleep(0); } sem.give(); } void co_entry_nogood(object ob, sync_object sem) { for (int i = 1 upto N) { ob=>no_good(); coroutine.sleep(0); } sem.give(); } // 合并域操作 public void test_two() { object ob = new_object(d3, domain.create()); sync_object sem = sync_object.create_semaphore(); // 其他协程等待域锁让出后执行 coroutine co1 = coroutine.create_in_thread("co1", domain.create(), (: co_entry_say2, ob, sem :)); coroutine co2 = coroutine.create_in_thread("co2", domain.create(), (: co_entry_nogood, ob, sem :)); sem.take(); sem.take(); printf("case total say: %d, failure times: %d\n", N, ob.get_failure_say_times()); ob.close(); sem.close(); } void co_entry_say2(object ob, sync_object sem) { for (int i = 1 upto N) { // 合并域操作 function.call_in_domain(ob.get_domain(), () { ob.good(); ob.say(); }); coroutine.sleep(0); } sem.give(); } ``` -------------------------------- ### 弱引用表接口 - 查询 Source: https://github.com/lyzz0612/gs_doc/blob/master/docs/Plugins/Doc_plugin_weakref.mdx 演示了如何使用`get()`方法从弱引用表中检索值。需要提供键作为参数。 ```C++ mixed val = wt.get("key"); ```