lu_ini source code
The complete source code of the lu_ini module (INI files). It is free to read, change and rebuild; a changed copy can be shipped with your own server in Modules/.
Download all files (lu_ini-source.zip)
Building
- Windows: run
build_win.cmd(Visual Studio 2012 or newer, 32 bit). The .dll is written toModules/. - Linux:
./build_linux.shbuilds the 32 bit .so in an Ubuntu 18.04 docker container, like the server. Copy the Squirrel headers of the server source (lu-server/squirrel/include) into asquirrel_include/folder next to the script first. sqapi.his the module API: the table of Squirrel functions the server hands toSQLoad(see Native modules).
build_linux.sh
12 lines
#!/bin/bash
# Builds lu_ini.so (32 bit ELF, libgcc / libstdc++ linked in) inside an Ubuntu 18.04 container, like the server (build_linux.sh in lu-server).
# Usage: ./build_linux.sh <folder that holds lu_ini.cpp, sqapi.h and the squirrel include dir> Output: ./lu_ini.so
set -e
cd "$(dirname "$0")"
docker run --rm -v "$PWD":/src -w /src ubuntu:18.04 bash -ec '
apt-get update -qq
apt-get install -y -qq --no-install-recommends g++-multilib >/dev/null
g++ -m32 -DSQUSEDOUBLE -shared -fPIC -O2 -Wall -fvisibility=hidden -static-libgcc -static-libstdc++ -I squirrel_include lu_ini.cpp -o lu_ini.so
'
echo "Done: lu_ini.so"
build_win.cmd
9 lines
@echo off
rem Builds lu_ini.dll (32 bit, static CRT: no msvcr dependency) with Visual Studio 2012. Output: ..\..\lu_ini.dll
call "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\vcvarsall.bat" x86 >nul
cd /d "%~dp0"
cl /nologo /DSQUSEDOUBLE /O2 /MT /LD /EHsc /W3 /D_CRT_SECURE_NO_WARNINGS /I..\..\..\lu-server\squirrel\include lu_ini.cpp /Fe..\..\lu_ini_new.dll /Fo%TEMP%\lu_ini.obj /link /SUBSYSTEM:WINDOWS,5.01
if exist ..\..\lu_ini_new.exp del ..\..\lu_ini_new.exp
if exist ..\..\lu_ini_new.lib del ..\..\lu_ini_new.lib
echo done %errorlevel%
lu_ini.cpp
766 lines
// lu_ini - INI file access for Liberty United server scripts (native module, rewrite of the original lu_ini.dll / lu_ini.so).
//
// ReadIniString(file, section, key) ReadIniInteger ReadIniFloat ReadIniBool value, or "" / 0 / 0.0 / false when it is missing
// ReadIniIndex(file, section, i) name of the i-th key of a section ("" when out of range)
// CountIniSection(file, section) number of keys of a section
// WriteIniString(file, section, key, value) WriteIniInteger WriteIniFloat WriteIniBool (return true)
// RemoveIniValue(file, section, key) DeleteIniSection(file, section) ClearIni(file) (return true)
//
// What is different from the original: the original parsed the whole file with iostreams on EVERY call and rewrote it on every
// write - a gamemode that read a few thousand values at start (Liberty Roleplay: ~25 s with the server frozen) now costs
// microseconds. Files are parsed once and cached (re-read when they change on disk); writes change the cached copy and are saved a
// few milliseconds later (SQPulse), in one atomic write per file, and always before the module unloads. A missing file no longer
// crashes the server: reads give the defaults, a write creates the file.
//
// The file format is the original's, so files written by either module read fine with the other:
// * "[Section]" headers, "Key = Value" lines written with CRLF, section / key order kept, comment lines (; or #) and blank lines kept
// * escapes: \\ \# \" in values (a # starts a trailing comment), \= in keys, \] in section names; any other \x reads as x
// * a value with leading / trailing blanks or line breaks is written in "double quotes"
// * duplicate keys: the last one wins; duplicate sections are merged; lines before the first header belong to section ""
// * names are case sensitive
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <string>
#include <vector>
#include <map>
#include "sqapi.h"
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <sys/types.h>
#include <sys/stat.h>
#define LU_EXPORT extern "C" __declspec(dllexport)
static unsigned int NowMs() { return (unsigned int)GetTickCount(); }
static bool StatFile(const char* p, unsigned long long* size, unsigned long long* mtime)
{
WIN32_FILE_ATTRIBUTE_DATA d;
if (!GetFileAttributesExA(p, GetFileExInfoStandard, &d)) return false;
*size = ((unsigned long long)d.nFileSizeHigh << 32) | d.nFileSizeLow;
*mtime = ((unsigned long long)d.ftLastWriteTime.dwHighDateTime << 32) | d.ftLastWriteTime.dwLowDateTime; // 100 ns units
return true;
}
static bool ReplaceFile(const char* tmp, const char* dst) { return MoveFileExA(tmp, dst, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0; }
#else
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#define LU_EXPORT extern "C" __attribute__((visibility("default")))
static unsigned int NowMs()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (unsigned int)(ts.tv_sec * 1000u + ts.tv_nsec / 1000000u);
}
static bool StatFile(const char* p, unsigned long long* size, unsigned long long* mtime)
{
struct stat st;
if (stat(p, &st) != 0) return false;
*size = (unsigned long long)st.st_size;
*mtime = (unsigned long long)st.st_mtim.tv_sec * 1000000000ull + (unsigned long long)st.st_mtim.tv_nsec;
return true;
}
static bool ReplaceFile(const char* tmp, const char* dst) { return rename(tmp, dst) == 0; }
#endif
static SQAPI g_api = NULL;
// ------------------------------------------------------------------------------------------------------------------------------
// the parsed file
// ------------------------------------------------------------------------------------------------------------------------------
enum { E_KEY = 0, E_COMMENT = 1, E_BLANK = 2 };
struct Entry
{
int kind;
std::string indent; // E_KEY: the blanks in front of the key as they were in the file
std::string key; // E_KEY
std::string value; // E_KEY (unescaped)
bool hasEq; // E_KEY: "key = value" (false: a bare "key")
std::string trail; // E_KEY: an inline comment ("# ...") that followed the value
std::string text; // E_COMMENT: the whole line
Entry() : kind(E_KEY), hasEq(false) {}
};
struct Section
{
std::string name;
std::vector<Entry> e;
std::map<std::string, size_t> idx; // key -> position in e
void Reindex()
{
idx.clear();
for (size_t i = 0; i < e.size(); i++) if (e[i].kind == E_KEY) idx[e[i].key] = i;
}
Entry* Find(const std::string& key)
{
std::map<std::string, size_t>::iterator it = idx.find(key);
return it == idx.end() ? NULL : &e[it->second];
}
};
struct IniFile
{
std::string path;
std::vector<Section> secs; // secs[0] is the part before the first header (name "")
std::map<std::string, size_t> sidx;
bool dirty;
unsigned int dirtySince;
bool exists;
unsigned long long size, mtime;
unsigned int lastCheck, lastUse;
IniFile() : dirty(false), dirtySince(0), exists(false), size(0), mtime(0), lastCheck(0), lastUse(0) {}
void ReindexSections()
{
sidx.clear();
for (size_t i = 0; i < secs.size(); i++) sidx[secs[i].name] = i;
}
Section* FindSection(const std::string& name)
{
std::map<std::string, size_t>::iterator it = sidx.find(name);
return it == sidx.end() ? NULL : &secs[it->second];
}
Section* GetSection(const std::string& name)
{
Section* s = FindSection(name);
if (s) return s;
Section ns;
ns.name = name;
secs.push_back(ns);
sidx[name] = secs.size() - 1;
return &secs[secs.size() - 1];
}
void Clear()
{
secs.clear(); sidx.clear();
Section pre; pre.name = "";
secs.push_back(pre);
sidx[""] = 0;
}
};
static std::map<std::string, IniFile*> g_files;
static std::string Trim(const std::string& s)
{
size_t a = 0, b = s.size();
while (a < b && (s[a] == ' ' || s[a] == '\t')) a++;
while (b > a && (s[b - 1] == ' ' || s[b - 1] == '\t' || s[b - 1] == '\r' || s[b - 1] == '\n')) b--;
return s.substr(a, b - a);
}
// ------------------------------------------------------------------------------------------------------------------------------
// parsing
// ------------------------------------------------------------------------------------------------------------------------------
static void AddKey(Section& sec, const std::string& indent, const std::string& key, const std::string& value, bool hasEq, const std::string& trail)
{
Entry* ex = sec.Find(key);
if (ex) // a duplicate key: the last one wins, the position stays
{
ex->value = value; ex->hasEq = hasEq; ex->trail = trail;
return;
}
Entry en;
en.kind = E_KEY; en.indent = indent; en.key = key; en.value = value; en.hasEq = hasEq; en.trail = trail;
sec.e.push_back(en);
sec.idx[key] = sec.e.size() - 1;
}
static void ParseText(IniFile& f, const std::string& text)
{
f.Clear();
size_t n = text.size(), p = 0;
if (n >= 3 && (unsigned char)text[0] == 0xEF && (unsigned char)text[1] == 0xBB && (unsigned char)text[2] == 0xBF) p = 3; // UTF-8 BOM
Section* cur = &f.secs[0];
size_t curIdx = 0;
while (p < n)
{
// one line (the line break is \n, \r\n or \r)
size_t ls = p;
while (p < n && text[p] != '\n' && text[p] != '\r') p++;
std::string line = text.substr(ls, p - ls);
if (p < n) { if (text[p] == '\r' && p + 1 < n && text[p + 1] == '\n') p += 2; else p++; }
size_t a = 0;
while (a < line.size() && (line[a] == ' ' || line[a] == '\t')) a++;
if (a >= line.size())
{
if (curIdx != 0) { Entry b; b.kind = E_BLANK; cur->e.push_back(b); } // blank lines of the part before the first header are dropped
continue;
}
char c0 = line[a];
if (c0 == ';' || c0 == '#')
{
Entry cm; cm.kind = E_COMMENT; cm.text = line;
cur->e.push_back(cm);
continue;
}
if (c0 == '[')
{
// [name] - the name ends at the first unescaped ]
std::string name;
size_t q = a + 1;
bool closed = false;
while (q < line.size())
{
char c = line[q];
if (c == '\\' && q + 1 < line.size()) { name += line[q + 1]; q += 2; continue; }
if (c == ']') { closed = true; break; }
name += c; q++;
}
if (closed)
{
name = Trim(name);
Section* s = f.FindSection(name);
if (!s) { s = f.GetSection(name); }
cur = s;
curIdx = (size_t)(s - &f.secs[0]);
continue;
}
Entry cm; cm.kind = E_COMMENT; cm.text = line; // a broken header: kept as it is
cur->e.push_back(cm);
continue;
}
// key [= value]
std::string indent = line.substr(0, a);
std::string key;
size_t q = a;
bool eq = false;
while (q < line.size())
{
char c = line[q];
if (c == '\\' && q + 1 < line.size()) { key += line[q + 1]; q += 2; continue; }
if (c == '=') { eq = true; q++; break; }
key += c; q++;
}
key = Trim(key);
std::string value, trail;
if (eq)
{
while (q < line.size() && (line[q] == ' ' || line[q] == '\t')) q++;
if (q < line.size() && line[q] == '"')
{
// "quoted value" - may span lines; \" is a quote, "\r\n" reads as "\n"
q++;
for (;;)
{
bool done = false;
while (q < line.size())
{
char c = line[q];
if (c == '\\' && q + 1 < line.size()) { value += line[q + 1]; q += 2; continue; }
if (c == '"') { done = true; q++; break; }
value += c; q++;
}
if (done || p >= n) break;
// the value goes on in the next line
value += '\n';
size_t ls2 = p;
while (p < n && text[p] != '\n' && text[p] != '\r') p++;
line = text.substr(ls2, p - ls2);
if (p < n) { if (text[p] == '\r' && p + 1 < n && text[p + 1] == '\n') p += 2; else p++; }
q = 0;
}
// what follows the closing quote: a comment, or nothing
while (q < line.size() && (line[q] == ' ' || line[q] == '\t')) q++;
if (q < line.size() && line[q] == '#') trail = line.substr(q);
}
else
{
size_t vs = q;
std::string raw;
while (q < line.size())
{
char c = line[q];
if (c == '\\' && q + 1 < line.size()) { raw += line[q + 1]; q += 2; continue; }
if (c == '#') { trail = line.substr(q); break; }
raw += c; q++;
}
(void)vs;
value = Trim(raw);
}
}
AddKey(*cur, indent, key, value, eq, trail);
}
}
static bool ReadWhole(const char* path, std::string& out)
{
FILE* fp = fopen(path, "rb");
if (!fp) return false;
char buf[8192];
size_t r;
out.clear();
while ((r = fread(buf, 1, sizeof(buf), fp)) > 0) out.append(buf, r);
fclose(fp);
return true;
}
// ------------------------------------------------------------------------------------------------------------------------------
// writing
// ------------------------------------------------------------------------------------------------------------------------------
static std::string EscapeKey(const std::string& k)
{
std::string o;
for (size_t i = 0; i < k.size(); i++)
{
char c = k[i];
if (c == '\\' || c == '=' || c == '#' || (i == 0 && (c == ';' || c == '['))) o += '\\';
o += c;
}
return o;
}
static std::string EscapeSection(const std::string& k)
{
std::string o;
for (size_t i = 0; i < k.size(); i++)
{
char c = k[i];
if (c == '\\' || c == ']') o += '\\';
o += c;
}
return o;
}
static std::string EscapeValue(const std::string& v)
{
bool quote = false;
if (!v.empty())
{
char f = v[0], b = v[v.size() - 1];
if (f == ' ' || f == '\t' || b == ' ' || b == '\t') quote = true;
if (v.find('\n') != std::string::npos || v.find('\r') != std::string::npos) quote = true;
}
std::string o;
if (quote) o += '"';
for (size_t i = 0; i < v.size(); i++)
{
char c = v[i];
if (c == '\\' || c == '#' || c == '"') { o += '\\'; o += c; }
else if (c == '\n') o += "\r\n";
else o += c;
}
if (quote) o += '"';
return o;
}
static void Serialize(const IniFile& f, std::string& out)
{
out.clear();
for (size_t si = 0; si < f.secs.size(); si++)
{
const Section& s = f.secs[si];
if (si != 0)
{
out += '[';
out += EscapeSection(s.name);
out += "]\r\n";
}
for (size_t i = 0; i < s.e.size(); i++)
{
const Entry& e = s.e[i];
if (e.kind == E_BLANK) { if (si != 0) out += "\r\n"; continue; }
if (e.kind == E_COMMENT) { out += e.text; out += "\r\n"; continue; }
out += e.indent;
out += EscapeKey(e.key);
if (e.hasEq || !e.value.empty())
{
if (e.value.empty()) { /* "key" alone: the original writes an empty value that way */ }
else { out += " = "; out += EscapeValue(e.value); }
}
if (!e.trail.empty()) { out += "\t "; out += e.trail; }
out += "\r\n";
}
}
}
static bool Flush(IniFile& f)
{
std::string data;
Serialize(f, data);
std::string tmp = f.path + ".tmp";
FILE* fp = fopen(tmp.c_str(), "wb");
if (!fp) { f.dirty = false; return false; }
bool ok = data.empty() || fwrite(data.data(), 1, data.size(), fp) == data.size();
ok = (fclose(fp) == 0) && ok;
if (ok) ok = ReplaceFile(tmp.c_str(), f.path.c_str());
if (!ok) remove(tmp.c_str());
f.dirty = false;
unsigned long long sz, mt;
if (StatFile(f.path.c_str(), &sz, &mt)) { f.size = sz; f.mtime = mt; f.exists = true; }
return ok;
}
// ------------------------------------------------------------------------------------------------------------------------------
// the file cache
// ------------------------------------------------------------------------------------------------------------------------------
static std::string NormalizePath(const char* p)
{
std::string s = p ? p : "";
for (size_t i = 0; i < s.size(); i++)
{
if (s[i] == '\\') s[i] = '/';
#ifdef _WIN32
s[i] = (char)tolower((unsigned char)s[i]);
#endif
}
return s;
}
static IniFile* Open(const char* path, bool create)
{
if (!path || !path[0]) return NULL;
unsigned int now = NowMs();
std::string key = NormalizePath(path);
IniFile* f = NULL;
std::map<std::string, IniFile*>::iterator it = g_files.find(key);
if (it != g_files.end()) f = it->second;
if (f)
{
f->lastUse = now;
if (!f->dirty) // somebody else may have changed the file (size + time of the last write, one cheap stat call)
{
f->lastCheck = now;
unsigned long long sz = 0, mt = 0;
bool ex = StatFile(path, &sz, &mt);
if (ex != f->exists || (ex && (sz != f->size || mt != f->mtime)))
{
std::string text;
f->exists = ex;
if (ex && ReadWhole(path, text)) { ParseText(*f, text); f->size = sz; f->mtime = mt; }
else f->Clear();
}
}
return f;
}
f = new IniFile;
f->path = path;
f->lastCheck = f->lastUse = now;
std::string text;
unsigned long long sz = 0, mt = 0;
if (StatFile(path, &sz, &mt) && ReadWhole(path, text)) { f->exists = true; f->size = sz; f->mtime = mt; ParseText(*f, text); }
else f->Clear();
g_files[key] = f;
(void)create;
return f;
}
static void MarkDirty(IniFile* f)
{
if (!f->dirty) { f->dirty = true; f->dirtySince = NowMs(); }
}
// ------------------------------------------------------------------------------------------------------------------------------
// the Squirrel functions
// ------------------------------------------------------------------------------------------------------------------------------
static bool GetStr(HSQUIRRELVM v, int idx, std::string& out)
{
const SQChar* s = NULL;
if (SQ_FAILED(g_api->getstring(v, idx, &s)) || !s) { out.clear(); return false; }
out = s;
return true;
}
// a value, or NULL
static const std::string* Lookup(HSQUIRRELVM v)
{
std::string file, sec, key;
if (!GetStr(v, 2, file) || !GetStr(v, 3, sec) || !GetStr(v, 4, key)) return NULL;
IniFile* f = Open(file.c_str(), false);
if (!f) return NULL;
Section* s = f->FindSection(Trim(sec));
if (!s) return NULL;
Entry* e = s->Find(Trim(key));
return e ? &e->value : NULL;
}
static SQInteger fnReadString(HSQUIRRELVM v)
{
const std::string* val = Lookup(v);
if (val) g_api->pushstring(v, val->c_str(), (SQInteger)val->size());
else g_api->pushstring(v, "", 0);
return 1;
}
static SQInteger fnReadInteger(HSQUIRRELVM v)
{
const std::string* val = Lookup(v);
long r = 0;
if (val) r = strtol(val->c_str(), NULL, 10); // like atoi: "12abc" is 12, "abc" is 0, out of range is clamped
if (r > INT_MAX) r = INT_MAX;
if (r < INT_MIN) r = INT_MIN;
g_api->pushinteger(v, (SQInteger)r);
return 1;
}
static SQInteger fnReadFloat(HSQUIRRELVM v)
{
const std::string* val = Lookup(v);
double r = 0.0;
if (val)
{
// atof of the C library: "12abc" is 12, "abc" is 0. Hex ("0x1F") and inf / nan are 0 on every platform (glibc would parse them)
const char* t = val->c_str();
while (*t == ' ' || *t == ' ') t++;
if (*t == '+' || *t == '-') t++;
if (*t == '.' || (*t >= '0' && *t <= '9'))
if (!(t[0] == '0' && (t[1] == 'x' || t[1] == 'X'))) r = atof(val->c_str());
}
g_api->pushdouble(v, (double)r);
return 1;
}
static bool IsTrue(const std::string& s)
{
std::string t;
for (size_t i = 0; i < s.size(); i++) t += (char)tolower((unsigned char)s[i]);
return t == "1" || t == "true" || t == "yes" || t == "on";
}
static SQInteger fnReadBool(HSQUIRRELVM v)
{
const std::string* val = Lookup(v);
g_api->pushbool(v, (val && IsTrue(*val)) ? SQTrue : SQFalse);
return 1;
}
static SQInteger fnReadIndex(HSQUIRRELVM v)
{
std::string file, sec;
SQInteger index = 0;
std::string r;
if (GetStr(v, 2, file) && GetStr(v, 3, sec) && SQ_SUCCEEDED(g_api->getinteger(v, 4, &index)))
{
IniFile* f = Open(file.c_str(), false);
Section* s = f ? f->FindSection(Trim(sec)) : NULL;
if (s && index >= 0)
{
SQInteger n = 0;
for (size_t i = 0; i < s->e.size(); i++)
{
if (s->e[i].kind != E_KEY) continue;
if (n == index) { r = s->e[i].key; break; }
n++;
}
}
}
g_api->pushstring(v, r.c_str(), (SQInteger)r.size());
return 1;
}
static SQInteger fnCount(HSQUIRRELVM v)
{
std::string file, sec;
SQInteger n = 0;
if (GetStr(v, 2, file) && GetStr(v, 3, sec))
{
IniFile* f = Open(file.c_str(), false);
Section* s = f ? f->FindSection(Trim(sec)) : NULL;
if (s) for (size_t i = 0; i < s->e.size(); i++) if (s->e[i].kind == E_KEY) n++;
}
g_api->pushinteger(v, n);
return 1;
}
static void SetValue(HSQUIRRELVM v, const std::string& value)
{
std::string file, sec, key;
bool ok = false;
if (GetStr(v, 2, file) && GetStr(v, 3, sec) && GetStr(v, 4, key))
{
std::string k = Trim(key);
IniFile* f = k.empty() ? NULL : Open(file.c_str(), true); // (an empty key cannot be written back and read again: refused)
if (f)
{
Section* s = f->GetSection(Trim(sec));
Entry* e = s->Find(k);
if (e) { e->value = value; e->hasEq = true; }
else
{
Entry en;
en.kind = E_KEY; en.key = k; en.value = value; en.hasEq = true;
s->e.push_back(en);
s->idx[k] = s->e.size() - 1;
}
MarkDirty(f);
ok = true;
}
}
g_api->pushbool(v, ok ? SQTrue : SQFalse);
}
static SQInteger fnWriteString(HSQUIRRELVM v)
{
std::string val;
GetStr(v, 5, val);
SetValue(v, val);
return 1;
}
static SQInteger fnWriteInteger(HSQUIRRELVM v)
{
SQInteger n = 0;
g_api->getinteger(v, 5, &n);
char b[32];
sprintf(b, "%d", (int)n);
SetValue(v, b);
return 1;
}
static SQInteger fnWriteFloat(HSQUIRRELVM v)
{
double fl = 0;
SQInteger n = 0;
if (g_api->gettype(v, 5) == OT_INTEGER) { g_api->getinteger(v, 5, &n); fl = (double)n; }
else g_api->getdouble(v, 5, &fl);
char b[64];
sprintf(b, "%g", (double)fl);
SetValue(v, b);
return 1;
}
static SQInteger fnWriteBool(HSQUIRRELVM v)
{
SQBool b = SQFalse;
g_api->getbool(v, 5, &b);
SetValue(v, b ? "true" : "false");
return 1;
}
static SQInteger fnRemoveValue(HSQUIRRELVM v)
{
std::string file, sec, key;
if (GetStr(v, 2, file) && GetStr(v, 3, sec) && GetStr(v, 4, key))
{
IniFile* f = Open(file.c_str(), false);
Section* s = f ? f->FindSection(Trim(sec)) : NULL;
if (s)
{
Entry* e = s->Find(Trim(key));
if (e)
{
s->e.erase(s->e.begin() + (e - &s->e[0]));
s->Reindex();
MarkDirty(f);
}
}
}
g_api->pushbool(v, SQTrue);
return 1;
}
static SQInteger fnDeleteSection(HSQUIRRELVM v)
{
std::string file, sec;
if (GetStr(v, 2, file) && GetStr(v, 3, sec))
{
IniFile* f = Open(file.c_str(), false);
std::string name = Trim(sec);
Section* s = f ? f->FindSection(name) : NULL;
if (s)
{
size_t i = (size_t)(s - &f->secs[0]);
if (i == 0) f->secs[0].e.clear(), f->secs[0].idx.clear(); // the part before the first header stays, empty
else { f->secs.erase(f->secs.begin() + i); f->ReindexSections(); }
MarkDirty(f);
}
}
g_api->pushbool(v, SQTrue);
return 1;
}
static SQInteger fnClear(HSQUIRRELVM v)
{
std::string file;
if (GetStr(v, 2, file))
{
IniFile* f = Open(file.c_str(), true);
if (f) { f->Clear(); MarkDirty(f); }
}
g_api->pushbool(v, SQTrue);
return 1;
}
static void FlushAll(bool onlyOld);
// FlushIni(): save what was written right now (writes are saved a few ms later by themselves; use this before another program reads the files)
static SQInteger fnFlush(HSQUIRRELVM v)
{
FlushAll(false);
g_api->pushbool(v, SQTrue);
return 1;
}
static void Register(HSQUIRRELVM v, const char* name, SQFUNCTION fn, int nargs, const char* mask)
{
char tm[16];
tm[0] = 't';
strncpy(tm + 1, mask, 12);
tm[13] = 0;
g_api->pushroottable(v);
g_api->pushstring(v, name, -1);
g_api->newclosure(v, fn, 0);
g_api->setparamscheck(v, nargs + 1, tm);
g_api->setnativeclosurename(v, -1, name);
g_api->newslot(v, -3, SQFalse);
g_api->pop(v, 1);
}
// ------------------------------------------------------------------------------------------------------------------------------
// module entry points
// ------------------------------------------------------------------------------------------------------------------------------
static void FlushAll(bool onlyOld)
{
unsigned int now = NowMs();
for (std::map<std::string, IniFile*>::iterator it = g_files.begin(); it != g_files.end(); ++it)
if (it->second->dirty && (!onlyOld || now - it->second->dirtySince >= 40)) Flush(*it->second);
}
LU_EXPORT SQRESULT SQLoad(HSQUIRRELVM v, SQAPI api)
{
g_api = api;
Register(v, "ReadIniString", fnReadString, 3, "sss");
Register(v, "ReadIniInteger", fnReadInteger, 3, "sss");
Register(v, "ReadIniFloat", fnReadFloat, 3, "sss");
Register(v, "ReadIniBool", fnReadBool, 3, "sss");
Register(v, "ReadIniIndex", fnReadIndex, 3, "ssi");
Register(v, "WriteIniString", fnWriteString, 4, "ssss");
Register(v, "WriteIniInteger", fnWriteInteger, 4, "sssi");
Register(v, "WriteIniFloat", fnWriteFloat, 4, "sssn");
Register(v, "WriteIniBool", fnWriteBool, 4, "sssb");
Register(v, "RemoveIniValue", fnRemoveValue, 3, "sss");
Register(v, "CountIniSection", fnCount, 2, "ss");
Register(v, "DeleteIniSection", fnDeleteSection, 2, "ss");
Register(v, "ClearIni", fnClear, 1, "s");
Register(v, "FlushIni", fnFlush, 0, "");
return 0;
}
LU_EXPORT SQRESULT SQUnload(void)
{
FlushAll(false);
for (std::map<std::string, IniFile*>::iterator it = g_files.begin(); it != g_files.end(); ++it) delete it->second;
g_files.clear();
return 0;
}
LU_EXPORT SQRESULT SQCallback(unsigned int callback, void* data)
{
(void)callback; (void)data;
return 0;
}
// every server tick: save what was written a moment ago, forget files nobody has used for a while
LU_EXPORT SQRESULT SQPulse(void)
{
static unsigned int lastSweep = 0;
if (g_files.empty()) return 0;
FlushAll(true);
unsigned int now = NowMs();
if (now - lastSweep >= 5000)
{
lastSweep = now;
for (std::map<std::string, IniFile*>::iterator it = g_files.begin(); it != g_files.end();)
{
if (!it->second->dirty && now - it->second->lastUse > 300000) { delete it->second; g_files.erase(it++); }
else ++it;
}
}
return 0;
}
sqapi.h
156 lines
// The SQAPI function table a native module receives in SQLoad() - identical to the one in lu-server/scripting.cpp (the original LU
// SquirrelModule SDK layout: the ORDER of the members is the ABI). Only the Squirrel types come from the server's headers.
#ifndef LU_SQAPI_H
#define LU_SQAPI_H
#include "squirrel.h"
typedef struct
{
/* VM */
HSQUIRRELVM (*open)(SQInteger initialstacksize);
HSQUIRRELVM (*newthread)(HSQUIRRELVM friendvm, SQInteger initialstacksize);
void (*seterrorhandler)(HSQUIRRELVM v);
void (*close)(HSQUIRRELVM v);
void (*setforeignptr)(HSQUIRRELVM v, SQUserPointer p);
SQUserPointer (*getforeignptr)(HSQUIRRELVM v);
void (*setprintfunc)(HSQUIRRELVM v, SQPRINTFUNCTION printfunc, SQPRINTFUNCTION errfunc);
SQPRINTFUNCTION (*getprintfunc)(HSQUIRRELVM v);
SQRESULT (*suspendvm)(HSQUIRRELVM v);
SQRESULT (*wakeupvm)(HSQUIRRELVM v, SQBool resumedret, SQBool retval, SQBool raiseerror, SQBool throwerror);
SQInteger (*getvmstate)(HSQUIRRELVM v);
/* Compiler */
SQRESULT (*compile)(HSQUIRRELVM v, SQLEXREADFUNC read, SQUserPointer p, const SQChar* sourcename, SQBool raiseerror);
SQRESULT (*compilebuffer)(HSQUIRRELVM v, const SQChar* s, SQInteger size, const SQChar* sourcename, SQBool raiseerror);
void (*enabledebuginfo)(HSQUIRRELVM v, SQBool enable);
void (*notifyallexceptions)(HSQUIRRELVM v, SQBool enable);
void (*setcompilererrorhandler)(HSQUIRRELVM v, SQCOMPILERERROR f);
/* Stack */
void (*push)(HSQUIRRELVM v, SQInteger idx);
void (*pop)(HSQUIRRELVM v, SQInteger nelemstopop);
void (*poptop)(HSQUIRRELVM v);
void (*remove)(HSQUIRRELVM v, SQInteger idx);
SQInteger (*gettop)(HSQUIRRELVM v);
void (*settop)(HSQUIRRELVM v, SQInteger newtop);
void (*reservestack)(HSQUIRRELVM v, SQInteger nsize);
SQInteger (*cmp)(HSQUIRRELVM v);
void (*move)(HSQUIRRELVM dest, HSQUIRRELVM src, SQInteger idx);
/* Object creation */
SQUserPointer (*newuserdata)(HSQUIRRELVM v, SQUnsignedInteger size);
void (*newtable)(HSQUIRRELVM v);
void (*newarray)(HSQUIRRELVM v, SQInteger size);
void (*newclosure)(HSQUIRRELVM v, SQFUNCTION func, SQUnsignedInteger nfreevars);
SQRESULT (*setparamscheck)(HSQUIRRELVM v, SQInteger nparamscheck, const SQChar* typemask);
SQRESULT (*bindenv)(HSQUIRRELVM v, SQInteger idx);
void (*pushstring)(HSQUIRRELVM v, const SQChar* s, SQInteger len);
void (*pushfloat)(HSQUIRRELVM v, float f); /* 32-bit float (old ABI): use pushdouble below */
void (*pushinteger)(HSQUIRRELVM v, SQInteger n);
void (*pushbool)(HSQUIRRELVM v, SQBool b);
void (*pushuserpointer)(HSQUIRRELVM v, SQUserPointer p);
void (*pushnull)(HSQUIRRELVM v);
SQObjectType (*gettype)(HSQUIRRELVM v, SQInteger idx);
SQInteger (*getsize)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*getbase)(HSQUIRRELVM v, SQInteger idx);
SQBool (*instanceof)(HSQUIRRELVM v);
void (*tostring)(HSQUIRRELVM v, SQInteger idx);
void (*tobool)(HSQUIRRELVM v, SQInteger idx, SQBool* b);
SQRESULT (*getstring)(HSQUIRRELVM v, SQInteger idx, const SQChar** c);
SQRESULT (*getinteger)(HSQUIRRELVM v, SQInteger idx, SQInteger* i);
SQRESULT (*getfloat)(HSQUIRRELVM v, SQInteger idx, float* f); /* 32-bit float (old ABI): use getdouble below */
SQRESULT (*getbool)(HSQUIRRELVM v, SQInteger idx, SQBool* b);
SQRESULT (*getthread)(HSQUIRRELVM v, SQInteger idx, HSQUIRRELVM* thread);
SQRESULT (*getuserpointer)(HSQUIRRELVM v, SQInteger idx, SQUserPointer* p);
SQRESULT (*getuserdata)(HSQUIRRELVM v, SQInteger idx, SQUserPointer* p, SQUserPointer* typetag);
SQRESULT (*settypetag)(HSQUIRRELVM v, SQInteger idx, SQUserPointer typetag);
SQRESULT (*gettypetag)(HSQUIRRELVM v, SQInteger idx, SQUserPointer* typetag);
void (*setreleasehook)(HSQUIRRELVM v, SQInteger idx, SQRELEASEHOOK hook);
SQChar* (*getscratchpad)(HSQUIRRELVM v, SQInteger minsize);
SQRESULT (*getclosureinfo)(HSQUIRRELVM v, SQInteger idx, SQUnsignedInteger* nparams, SQUnsignedInteger* nfreevars);
SQRESULT (*setnativeclosurename)(HSQUIRRELVM v, SQInteger idx, const SQChar* name);
SQRESULT (*setinstanceup)(HSQUIRRELVM v, SQInteger idx, SQUserPointer p);
SQRESULT (*getinstanceup)(HSQUIRRELVM v, SQInteger idx, SQUserPointer* p, SQUserPointer typetag);
SQRESULT (*setclassudsize)(HSQUIRRELVM v, SQInteger idx, SQInteger udsize);
SQRESULT (*newclass)(HSQUIRRELVM v, SQBool hasbase);
SQRESULT (*createinstance)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*setattributes)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*getattributes)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*getclass)(HSQUIRRELVM v, SQInteger idx);
void (*weakref)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*getdefaultdelegate)(HSQUIRRELVM v, SQObjectType t);
/* Object manipulation */
void (*pushroottable)(HSQUIRRELVM v);
void (*pushregistrytable)(HSQUIRRELVM v);
void (*pushconsttable)(HSQUIRRELVM v);
SQRESULT (*setroottable)(HSQUIRRELVM v);
SQRESULT (*setconsttable)(HSQUIRRELVM v);
SQRESULT (*newslot)(HSQUIRRELVM v, SQInteger idx, SQBool bstatic);
SQRESULT (*deleteslot)(HSQUIRRELVM v, SQInteger idx, SQBool pushval);
SQRESULT (*set)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*get)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*rawget)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*rawset)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*rawdeleteslot)(HSQUIRRELVM v, SQInteger idx, SQBool pushval);
SQRESULT (*arrayappend)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*arraypop)(HSQUIRRELVM v, SQInteger idx, SQBool pushval);
SQRESULT (*arrayresize)(HSQUIRRELVM v, SQInteger idx, SQInteger newsize);
SQRESULT (*arrayreverse)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*arrayremove)(HSQUIRRELVM v, SQInteger idx, SQInteger itemidx);
SQRESULT (*arrayinsert)(HSQUIRRELVM v, SQInteger idx, SQInteger destpos);
SQRESULT (*setdelegate)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*getdelegate)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*clone)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*setfreevariable)(HSQUIRRELVM v, SQInteger idx, SQUnsignedInteger nval);
SQRESULT (*next)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*getweakrefval)(HSQUIRRELVM v, SQInteger idx);
SQRESULT (*clear)(HSQUIRRELVM v, SQInteger idx);
/* Calls */
SQRESULT (*call)(HSQUIRRELVM v, SQInteger params, SQBool retval, SQBool raiseerror);
SQRESULT (*resume)(HSQUIRRELVM v, SQBool retval, SQBool raiseerror);
const SQChar* (*getlocal)(HSQUIRRELVM v, SQUnsignedInteger level, SQUnsignedInteger idx);
const SQChar* (*getfreevariable)(HSQUIRRELVM v, SQInteger idx, SQUnsignedInteger nval);
SQRESULT (*throwerror)(HSQUIRRELVM v, const SQChar* err);
void (*reseterror)(HSQUIRRELVM v);
void (*getlasterror)(HSQUIRRELVM v);
/* Raw object handling */
SQRESULT (*getstackobj)(HSQUIRRELVM v, SQInteger idx, HSQOBJECT* po);
void (*pushobject)(HSQUIRRELVM v, HSQOBJECT obj);
void (*addref)(HSQUIRRELVM v, HSQOBJECT* po);
SQBool (*release)(HSQUIRRELVM v, HSQOBJECT* po);
void (*resetobject)(HSQOBJECT* po);
const SQChar* (*objtostring)(HSQOBJECT* o);
SQBool (*objtobool)(HSQOBJECT* o);
SQInteger (*objtointeger)(HSQOBJECT* o);
float (*objtofloat)(HSQOBJECT* o);
SQRESULT (*getobjtypetag)(HSQOBJECT* o, SQUserPointer* typetag);
/* GC */
SQInteger (*collectgarbage)(HSQUIRRELVM v);
/* Serialization */
SQRESULT (*writeclosure)(HSQUIRRELVM vm, SQWRITEFUNC writef, SQUserPointer up);
SQRESULT (*readclosure)(HSQUIRRELVM vm, SQREADFUNC readf, SQUserPointer up);
/* Memory */
void* (*malloc)(SQUnsignedInteger size);
void* (*realloc)(void* p, SQUnsignedInteger oldsize, SQUnsignedInteger newsize);
void (*free)(void* p, SQUnsignedInteger size);
/* Debug */
SQRESULT (*stackinfos)(HSQUIRRELVM v, SQInteger level, SQStackInfos* si);
void (*setdebughook)(HSQUIRRELVM v);
/* 0.5.1: 64-bit floats (the server's scripts use doubles; modules are built with SQUSEDOUBLE) */
void (*pushdouble)(HSQUIRRELVM v, double f);
SQRESULT (*getdouble)(HSQUIRRELVM v, SQInteger idx, double* f);
} SquirrelAPI;
typedef SquirrelAPI* SQAPI;
#endif
Categories: Native modules