ريسورسات RedM تشتغل على Lua 5.4 إذا الـ manifest فيه lua54 'yes'. هذي الصفحة تغطي اللغة زي ما تستخدمها في الريسورسات، مع الإضافات اللي يعطيها Cfx.re. الدليل الكامل للغة على lua.org/manual/5.4.
القيم والأنواع
Lua فيها ثمانية أنواع: nil، boolean، number، string، table، function، thread (coroutine) و userdata.
print(type(nil), type(true), type(10), type(1.5), type('x'), type({}), type(print))
-- nil boolean number number string table function- بس
nilوfalseتعتبر false.0و''تعتبر true. - الأرقام إما أعداد صحيحة أو عشرية.
10 // 3قسمة صحيحة (3)، و10 / 2دائماً عشري (5.0)، وmath.type(5)ترجع'integer'. - النصوص سلاسل بايتات ما تتغير. استخدم
..للدمج و#sللطول بالبايت.
المتغيرات والنطاق
local count = 0 -- local to the block: always prefer this
globalVar = 1 -- global: shared by every file of the resource, avoid
local a, b = 1, 2 -- multiple assignment
a, b = b, a -- swap
local max <const> = 100 -- constant (5.4): assignment is an errorالـ local يكون ظاهر لين نهاية الكتلة (do ... end، دالة، جسم حلقة). المتغيرات المحلية أسرع من العامة وما يقدر سكربت ثاني يكتب فوقها.
العوامل (Operators)
| النوع | العوامل (Operators) |
|---|---|
| الحساب | + - * / // % ^ (^ للأُس، ودائماً عشري) |
| المقارنة | == ~= < <= > >= (لا يساوي هي ~=، مو !=) |
| المنطق | and or not (a and b or c هو الشرط الثلاثي المعتاد) |
| النصوص | .. للدمج، # للطول |
| عمليات البت | & \| ~ << >> ~ (~ is xor when binary, not when unary) |
local label = player and player.name or 'unknown'
local half = total // 2سير التنفيذ
if hp <= 0 then
die()
elseif hp < 30 then
limp()
else
walk()
end
for i = 1, 10 do end -- 1..10
for i = 10, 1, -1 do end -- counting down
for i, v in ipairs(list) do end -- array part, in order, stops at the first nil
for k, v in pairs(map) do end -- every key, order not guaranteed
while cond do end
repeat until condbreak يطلع من الحلقة. goto continue مع label ::continue:: في آخر جسم الحلقة هي الطريقة المعتادة لـ "التكرار التالي".
الدوال
local function add(a, b) return a + b end
local function stats(list)
return #list, list[1] -- several return values
end
local n, first = stats({4, 5, 6})
local function log(fmt, ...) -- variable arguments
print(string.format(fmt, ...))
end
local fn = function(x) return x * 2 end -- anonymous function / closureالدوال قيم، والـ closures تحتفظ بالمتغيرات المحلية اللي تستخدمها. select('#', ...) يعد المعاملات، و table.pack(...) يجمعها، و table.unpack(t) يفرد الجدول.
الجداول
الجدول هو هيكل البيانات الوحيد: هو المصفوفة والخريطة والكائن والمجموعة.
local list = { 'a', 'b', 'c' } -- list[1] == 'a' (Lua starts at 1)
local map = { name = 'Arthur', cash = 12.5 }
local set = { police = true, doctor = true } -- fast membership test: set[job]
list[#list + 1] = 'd' -- append
table.insert(list, 'e')
table.insert(list, 1, 'first') -- insert at position
table.remove(list, 1) -- remove at position
print(#list) -- length of the array part| الدالة | الاستخدام |
|---|---|
table.insert(t, [pos,] v) / table.remove(t [, pos]) |
إضافة أو حذف عنصر. |
table.concat(t, sep) |
دمج النصوص، أسرع بكثير من .. داخل حلقة. |
table.sort(t [, cmp]) |
ترتيب في نفس المكان. المقارنة لازم تكون "أصغر من" صارمة. |
table.unpack(t, i, j) / table.pack(...) |
فرد أو جمع القيم. |
table.move(a, f, e, t [, a2]) |
نسخ مدى. |
next(t) |
nil لما يكون الجدول فاضي، وأرخص من العد. |
انتبه: #t موثوق بس في المصفوفات بدون فراغات. تعيين nil يحذف المفتاح. الجداول تنمرر بالمرجع: انسخها بحلقة إذا تحتاج نسخة مستقلة.
local function deepCopy(v)
if type(v) ~= 'table' then return v end
local out = {}
for k, x in pairs(v) do out[k] = deepCopy(x) end
return out
endالنصوص
local s = 'Hello'
print(s:upper(), s:lower(), s:len(), s:sub(2, 4), s:rep(2, '-'))
print(('%s has $%.2f'):format('Arthur', 12.5))
print(('a,b,c'):find(',', 1, true)) -- plain search: start, end
for word in ('one two'):gmatch('%a+') do print(word) end
print(('x=1'):gsub('%d', '9')) -- replace, returns text and countرموز string.format: %s نص، %d عدد صحيح، %f / %.2f عشري، %x hex، %q بين علامات تنصيص، %% علامة نسبة.
الأنماط (Patterns) مو تعابير نمطية (regex):
| الكلاس | يطابق | المكرر | المعنى | |
|---|---|---|---|---|
%a |
حرف | * |
0 أو أكثر | |
%d |
رقم | + |
1 أو أكثر | |
%s |
مسافة | - |
0 أو أكثر، الأقصر | |
%w |
حرف أو رقم | ? |
0 أو 1 | |
%p |
علامات ترقيم | ^ / $ |
بداية / نهاية النص | |
. |
أي حرف | ( ) |
التقاط |
اهرب من الحرف الخاص بـ %: %. نقطة حرفية.
الـ Metatables
الـ metatable يغيّر تصرف الجدول. هي طريقة بناء الكلاسات.
local Vec = {}
Vec.__index = Vec
function Vec.new(x, y) return setmetatable({ x = x, y = y }, Vec) end
function Vec:len() return math.sqrt(self.x ^ 2 + self.y ^ 2) end
Vec.__add = function(a, b) return Vec.new(a.x + b.x, a.y + b.y) end
Vec.__tostring = function(v) return ('(%s, %s)'):format(v.x, v.y) end
local v = Vec.new(3, 4) + Vec.new(0, 0)
print(v:len(), tostring(v)) -- 5.0 (3, 4)الـ metamethods الشائعة: __index، __newindex، __call، __tostring، __len، __eq، __lt، __le، __concat، __close، وعائلة الحساب (__add، __sub، __mul، __div، ...). obj:method(x) اختصار لـ obj.method(obj, x).
الأخطاء
local ok, err = pcall(function() error('boom') end)
if not ok then print('failed:', err) end
local ok2, res = xpcall(risky, debug.traceback) -- keeps the stack trace
assert(type(x) == 'number', 'x must be a number')لفّ الكود اللي ممكن يفشل بسبب مدخلات خارجية (JSON، نتائج قاعدة البيانات) بـ pcall؛ ولا تخبّي أخطاءك فيه.
الرياضيات
math.floor, math.ceil, math.abs, math.min, math.max, math.sqrt, math.sin, math.cos, math.pi, math.huge, math.random(m, n), math.randomseed(x), math.tointeger(x), math.fmod(a, b).
local function round(n, places)
local m = 10 ^ (places or 0)
return math.floor(n * m + 0.5) / m
endلا تستخدم math.random أبد لشي لازم يكون عادل أو سري (مكافآت مهمة، رموز): سوّ السحب في السيرفر وافحصه.
Coroutines#
local co = coroutine.create(function(a)
local b = coroutine.yield(a + 1)
return b * 2
end)
print(coroutine.resume(co, 1)) -- true 2
print(coroutine.resume(co, 10)) -- true 20في RedM نادراً تنشئ coroutines بنفسك: CreateThread و Wait يسوونها عنك.
وش يضيف Cfx.re
| الميزة | مثال |
|---|---|
| hash حرفي | `a_c_horse_arabian_white` يعطي hash الموديل |
| الـ Vectors | vector3(1.0, 2.0, 3.0)، vec3، vector2، vector4؛ + - *، #v الطول، .x .y .z |
json |
json.encode(t), json.decode(s) |
| التعيين المركّب | n += 1، s ..= 'x' (Cfx فقط) |
| التنقل الآمن | config?.blip?.sprite يرجع nil بدل خطأ |
| Threads | CreateThread(fn), Wait(ms), SetTimeout(ms, fn) |
| Promises | promise.new(), Citizen.Await(p) |
| الأحداث (Events) | RegisterNetEvent, AddEventHandler, TriggerEvent, TriggerServerEvent, TriggerClientEvent |
| الـ Exports | exports('Name', fn) و exports.resource:Name() |
| Msgpack | msgpack.pack, msgpack.unpack |
إضافات Cfx مو Lua عادية: المحرر أو الـ linter اللي ما يدعم Cfx ممكن يعتبرها أخطاء، والكود ما يشتغل برا اللعبة.
الأداء
- خلّ الحلقات السريعة بدون إنشاء جداول ولا دمج نصوص.
- خزّن
PlayerPedId()وGetEntityCoords(ped)والـ natives المشابهة مرة وحدة في كل دورة. - استخدم جدول كـ مجموعة لفحص الوجود (
allowed[job]) بدل ما تلف على مصفوفة. - ابنِ النص بـ
table.concat، مو..داخل حلقة. - الانتظار:
Wait(1000)وقت الخمول، وWait(0)بس وقت ما فيه شي ظاهر يحتاج كل فريم. - تجنب
pairsعلى جداول ضخمة في حلقات الفريم؛ خلّ قائمة محسوبة مسبقاً.
أخطاء شائعة
| الخطأ | الحل |
|---|---|
if x != 1 |
استخدم ~= |
list[0] |
مصفوفات Lua تبدأ من 1 |
استخدام متغير عام بالغلط (coords = ...) |
اكتب local coords |
string.sub تبدأ من 0 |
ابدأ من 1 |
مقارنة عدد عشري بعدد صحيح بـ == في الفلوس |
قرّب للهللات وقارن أعداد صحيحة |
| انتظار قيمة من الكلاينت في السيرفر | اسأل الكلاينت بـ callback وافحص الجواب |
الشكر والمصادر
Lua من إنشاء PUC-Rio ومنشورة برخصة MIT. النص المعتمد هو Lua 5.4 Reference Manual.