Kenix Posted May 7, 2011 Posted May 7, 2011 (edited) Математические функции Функция: math.equation float/int, float/int math.equation ( int/float nA, int/float nB, int/float nC ) function math.equation( nA, nB, nC ) if type( nA ) == 'number' and type( nB ) == 'number' and type( nC ) == 'number' then local nRoot = math.sqrt( nB ^ 2 - 4 * nA * nC ) if tostring( nRoot ):find '-nan' then return nil end local nX1, nX2 = ( -nB + nRoot ) / ( 2 * nA ), ( -nB - nRoot ) / ( 2 * nA ) return nX1 == math.ceil( nX1 ) and nX1 or tonumber( string.format( '%.1f', nX1 ) ), nX2 == math.ceil( nX2 ) and nX2 or tonumber( string.format( '%.1f', nX2 ) ) end return false end Пример local aCount = { { nA = 5, nB = -3, nC = -2 }; { nA = 1, nB = -0.4, nC = 0.04 }; } for _, a in ipairs( aCount ) do print( math.equation( a.nA, a.nB, a.nC ) ) end 1 -0.4 0.2 0.2 Автор: Kenix Функция: math.double int math.double( int number ) Обязательные аргументы number:Десятичное число. Возврат Возвращает двоичное число. function math.double( number ) if type( number ) == 'number' then local function check( n ) if n == math.floor( n ) then return 0 else return 1 end end local t = { } while math.floor( number ) ~= 0 do if math.floor( number ) == 0 then break end number = math.floor( number )/2 t[ #t + 1 ] = check( number ) end local numb = '' for _,v in pairs( t ) do numb = v..numb end return tonumber( numb ) end return false end Пример outputDebugString( "-->"..tostring( math.double( 60 ) ) ) -->111100 Автор: Kenix [*]Функция: math.rating float math.rating( int iLikes, int iTotal, [ table aVotesRange, float fFactor ] ) Обязательные аргументы iLikes:Число положительных голосов. iTotal:Общее число голосов. Необязательные аргументы aVotesRange:Диапазон голосов. fFactor :Коэффициент. Возврат Возвращает рейтинг по формуле Вильсона. function math.rating( iLikes, iTotal, aVotesRange, fFactor ) if type( iLikes ) == "number" and type( iTotal ) == "number" then if type( aVotesRange ) ~= "table" then aVotesRange = { 0, 10 }; end if type( fFactor ) ~= "number" then fFactor = 0.54485; end if iLikes == 0 then return 0; end local Min = math.min( unpack( aVotesRange ) ); local Width = math.max( unpack( aVotesRange ) ) - Min; local fPhat = ( iLikes - iTotal * Min ) / Width / iTotal local fRating = ( fPhat + fFactor * fFactor / ( 2 * iTotal ) - fFactor * math.sqrt( ( fPhat * ( 1 - fPhat ) + fFactor * fFactor / ( 4 * iTotal ) ) / iTotal ) ) / ( 1 + fFactor * fFactor / iTotal ); return fRating * Width + Min; end return false; end Примеры local iLikes = 100; local iDislikes = 50; -- Рейтинг по 10 бальной шкале outputDebugString( "--> ".. math.rating( iLikes, iLikes + iDislikes ) * 10 ) --> 5.6403584209109 local iLikes = 1; local iDislikes = 50; -- Рейтинг в процентах outputDebugString( "--> ".. math.rating( iLikes, iLikes + iDislikes ) * 100 ) --> 0.41217338613396 local iLikes = 1000; local iDislikes = 50; -- Рейтинг в процентах outputDebugString( "--> ".. math.rating( iLikes, iLikes + iDislikes ) * 100 ) --> 90.416102212328 Автор: Kenix [*]Функция: math.float bool/int math.float( float/int n,[ bool bConvert, string sType ] ) Обязательные аргументы n:Число для проверки. Необязательные аргументы bConvert:Конвертировать в целое. sType:Тип конверта 'floor' или 'ceil'. Возврат Возвращает истину если число с плавающей точкой. function math.float( n, bConvert, sType ) if type( n ) == 'number' then local sType = type( sType ) ~= 'string' and 'floor' or sType ~= 'floor' and sType ~= 'ceil' and 'floor' or sType if n == math[ sType ]( n ) then return false else if not bConvert then return true end return math[ sType ]( n ) end end return false end Примеры outputDebugString( "--> "..tostring( math.float( 100.1 ) ) ) --> true outputDebugString( "--> "..tostring( math.float( 100.1, true, 'ceil' ) ) ) --> 101 Автор: Kenix [*]Функция math.decl string math.decl ( int nubmer, string declin1, string declin2, string declin3 ) function math.decl( number, declin1, declin2, declin3 ) if number % 10 == 1 and number % 100 ~= 11 then return declin1; elseif number % 10 >= 2 and number % 10 <= 4 and ( number % 100 < 10 or number % 100 >= 20 ) then return declin2; end return declin3; end Пример использования print( "Вы были тут 13 " .. math.decl( 13, 'час', 'часа', 'часов' ) .. ' назад' ); -- Вы были тут 13 часов назад print( "Забанен на 124 " .. math.decl( 124, 'минуту', 'минуты', 'минут' ) ); -- Забанен на 124 минуты Автор: Kernell [*]Функция math.clamp Синтаксис float/int math.clamp ( float/int value, float/int lower, float/int upper ) Аргументы value: Значение lower: Нижнее значение upper: Верхнее значение Возврат Возвращает число в пределах lower и upper значений. Код function math.clamp ( value, lower, upper ) if type ( value ) == "number" and type ( lower ) == "number" and type ( upper ) == "number" then if value < lower then value = lower elseif value > upper then value = upper end return value end return false end Автор: TEDERIs Функции для работы с таблицами Функция: table.sortIndex table table.sortIndex( table tab ) Обязательные аргументы tab :Таблица, которую нужно отсортировать по индексам, не меняя порядок значений. Возврат Возвращает таблицу отсортированную по индексам. Если первый аргумент при вызове функции не таблица, то вернёт ложь. function table.sortIndex( tab ) if type( tab ) ~= 'table' then return false; end local max = 1 for i, n in pairs( tab ) do if type( i ) == 'number' and max < i then max = i end end for i = max, 1, -1 do if tab[i] == nil then for k = i, max do tab[k] = tab[k+1] end end end return true end Пример local t = { [2] = 3; [5] = 2; [7] = 1; [10] = 16; [9] = false; } table.sortIndex( t ) for i, n in ipairs( t ) do print( i, n ) end --[[ 1 3 2 2 3 1 4 false 5 16 --]] Автор: TheNormalnij [*]Функция: table.max int,int table.max ( table t ) Обязательные аргументы t:Таблица. Возврат Возвращает индекс и максимальное значение. Если первый аргумент при вызове функции не таблица, то вернёт ложь. function table.max( t ) if type( t ) == 'table' then local key = false local count = 0 for index,value in pairs( t ) do if tonumber( count ) < tonumber( value ) then count = value key = index end end return key,count end return false end Пример print( '-->',table.max( { [1] = 0;[2] = 1 } ) ) --> 2 1 Автор: Kenix [*]Функция: table.min int,int table.min ( table t ) Обязательные аргументы t:Таблица. Возврат Возвращает индекс и минимальное значение. Если первый аргумент при вызове функции не таблица, то вернёт ложь. function table.min( t ) if type( t ) == 'table' then local key = false local count = math.huge for index,value in pairs( t ) do if tonumber( count ) > tonumber( value ) then count = value key = index end end return key,count end return false end Пример print( '-->',table.min( { [1] = 3; [2] = 4 } ) ) --> 1 3 Автор: Kenix [*]Функция: table.serialize string table.serialize ( table t ) Обязательные аргументы t:- таблица для сериализации Возврат Возвращает строку сериализованной таблицы, либо ложь. function table.serialize( t ) if not t or type( t ) ~= 'table' then return false end -- if nil or not a table local buf = '{' for key,value in pairs( t ) do local v_type,k_type = type( value ),type( key ) if v_type ~= 'userdata' and k_type ~= 'userdata' -- ignore fields and keys witch contain userdata, thread or function and v_type ~= 'thread' and k_type ~= 'thread' and v_type ~= 'function' and k_type ~= 'function' then if k_type == 'number' then buf = buf .. '['..key..'] = ' else buf = buf .. '[\''..key..'\'] = ' end if v_type == 'table' then value = table.serialize( value ) elseif v_type == 'string' then value = '\''..value..'\'' else value = tostring( value ) end buf = buf .. value if next( t,key ) then buf = buf..',' end end end return buf .. '}' end Автор: LoveFist [*]Функция: table.deserialize table table.deserialize( string s ) Обязательные аргументы s:- строка для десериализации Возврат Возвращает таблицу, либо ложь. function table.deserialize( s ) if type( s ) == 'string' then local getTableFromString = loadstring( 'return '..s ) local t = getTableFromString( ) if type( t ) ~= 'table' then return false end return t end return false end Автор: LoveFist Примеры к этим 2 функциям. local test = {[1] = 'dw', ['2'] = 123, [3] = {1,2,'ere'}} local tString = table.serialize(test) print(tString)--> {[1] = 'dw', [3] = {[1] = 1, [2] = 2, [3] = 'ere'}, ['2'] = 123} local sTable = table.deserialize(tString) print(sTable[1]..', '..sTable['2'])--> dw, 123 [*]Функция: table.replace table ,table table.replace ( table t, table/string/number/bool condition, table/string/number/bool repl ) Обязательные аргументы t:Таблица. condition:Условие. repl:Замена. Возврат Возвращает новую таблицу и ссылку на старую таблицу. function table.replace( t,condition,repl ) if type( t ) == "table" then if type( condition ) == "number" or type( condition ) == "string" or type( condition ) == "boolean" and type( repl ) == "number" or type( repl ) == "string" or type( repl ) == "boolean" then local old = t local new = { } for i,v in pairs( old ) do if v == condition then new[ i ] = repl else new[ i ] = v end end return new,old elseif type( condition ) == "table" and type( repl ) == "table" then local old = t local new = { } for i,v in pairs( old ) do if v == condition[ i ] then new[ i ] = repl[ i ] else new[ i ] = v end end return new,old end return false end return false end Пример local t = { "Player1","Player2" } table.replace( t, { "Player1", "Player2" }, { "Guy1", "Guy2" } ) -- заменяет Player1 и Player2 на Guy1 и Guy2 Автор: Kenix [*]Функция для удаления значения из таблицы по маске индекса function fRemoveTableFieldsByPattern ( t, sPattern ) if type(t) ~= 'table' or type(sPattern) ~= 'string' then return false end for index, _ in pairs(t) do if string.find( tostring(index), sPattern ) then if type(index) == 'number' then table.remove(t, index) else t[index] = nil end end end return true end Примеры local t = { [123] = 1, [456] = 2, [789] = 3, ["159"] = 4, last = 4 } fRemoveTableFieldsByPattern( t, '^%d+$' ) -- удалить все индексы, состоящие только из цифр -- в таблице t осталось только поле 'last' local t = { ['playerHealth'] = 100, ['playerArmour'] = 0, ['playerMoney'] = 123456, ['onlinePlayersCount'] = 0 } fRemoveTableFieldsByPattern( t, '^player' ) -- удалить все индексы, начинающиеся со слова 'player' -- в таблице t осталось только поле 'onlinePlayersCount' По желанию можно также удалять по маске значения, а не индекса. У меня просто в таблицах некоторые группы полей начинают с одного и того же слова, их много, и вручную каждый раз удалять их - слишком много места в коде. Автор: MX_Master [*]Функция: table.random var table.random ( table Table, [ int row, bool randomline ] ) Обязательные аргументы Table:Таблица. Необязательные аргументы row:Строка. randomline:Случайная строка и элемент в этой строке. Возврат Возвращает случайный элемент из таблицы. function table.random ( Table,row,randomline ) local size if type( Table ) ~= 'table' then return false end if not row and not randomline then local row,randomline = false,false end if row and type( row ) ~= 'number' then return false end if randomline and type( randomline ) ~= 'boolean' then return false end function size( Table ) if type(t) ~= 'table' then return false end local var = 0 for _ in pairs( Table ) do var = var + 1 end return var end if row then local key = math.random( 1, size( Table ) ) return Table[ row ][ math.random( 1, size ( Table[ key ] ) ) ] end if randomline then local key = math.random( 1, size( Table ) ) return Table[ key ][ math.random( 1, size( Table[ key ] ) ) ] end return Table[ math.random( 1,size( Table ) ) ] end Автор: Kenix [*]Функция: table.last var,int table.last ( table t ) Обязательные аргументы t:Таблица. Возврат Возвращает конечное значение и индекс из цикла. function table.last( t ) if type( t ) ~= "table" then return false end local el,numb = false,0 for i,v in pairs( t ) do el,numb = v,i end return el,numb end Автор: Kenix [*]Функция: table.empty bool table.empty ( table t ) Обязательные аргументы t:Таблица. Возврат Возвращает истину если таблица пуста. function table.empty( t ) if type( t ) ~= "table" then return false end return not next( t ) end Автор: Kenix [*]Функция: table.size int/bool table.size ( table t ) Обязательные аргументы t:Таблица. Возврат Возвращает длину таблицы. function table.size( t ) if type( t ) ~= 'table' then return false end local n = 0 for _ in pairs( t ) do n = n + 1 end return n end Автор: Kenix [*]Функция: table.find bool table.find ( table a, string/int/float Find , [ bool bFindEveryWhere ] ) Обязательные аргументы a:Таблица. Find:Строка/число Необязательные аргументы bFindEveryWhere:Искать везде. Возврат Возвращает истину если элемент был найден. function table.find ( a , Find, bFindEveryWhere ) if type( a ) == 'table' and type( Find ) == 'string' or type( Find ) == 'number' then local function TableDimension( a ) local aResult = { } for _, value in pairs( a ) do if type( value ) == 'table' then for _, v in pairs( TableDimension( value ) ) do table.insert( aResult, v ) end else table.insert( aResult, value ) end end return aResult end local aReturn if type( bFindEveryWhere ) == 'boolean' then aReturn = TableDimension( a ) else aReturn = a end local bReturn = false for _ , v in pairs( aReturn ) do if v == Find then bReturn = true end end return bReturn end return false end Автор: Kenix Функции для работы со строками Функция: string.transfer string/bool string.transfer( string s, int nMax ) Обязательные аргументы s:Строка. nMax:Перенос строки (см. пример). Возврат Возвращает строку function string.transfer( s, nMax ) if type( s ) == 'string' and type( nMax ) == 'number' then local nMaxOld = nMax local nLength = utfLen( s ); if nLength >= nMax then local sNew = '' local nStart = 0 for nCount = 1, math.ceil( nLength / nMax ) do sNew = sNew .. '\n'.. utfSub( s, nStart + 1, nMax ) nStart = nMax nMax = nMax + nMaxOld end return utfSub( sNew, 2, #sNew ) end return s end return false end Примеры outputDebugString( string.transfer( "abc", 2 ) ) --[[ ab c ]] outputDebugString( string.transfer( "abc", 3 ) ) -- abc outputDebugString( string.transfer( "abcdef", 3 ) ) --[[ abc def ]] Автор: Kenix [*]Функция: string.trim string/bool string.trim( string str ) Обязательные аргументы str:Строка. Возврат Возвращает строку с убранными пробелами в начале и в конце. function string.trim( str ) if type( str ) == "string" then str = string.gsub( str, "^%s*", "" ) str = string.gsub( str, "%s*$", "" ) return str end return false end Автор: Fro Функции для работы с цветом Функция: HSLtoRGB bool/r,g,b HSLtoRGB ( int H, int S, int L ) Обязательные аргументы H:тон. S:насыщенность. L:яркость. что это? function HSLtoRGB(H, S, L) if type( H ) == "number" and type( S ) == "number" and type( L ) == "number" then local r, g, b S = S / 100 L = L / 100 if S == 0 then r = L * 255.0 g = L * 255.0 b = L * 255.0 else if L < 0.5 then Q = L * (1.0 + S) else Q = L + S - (L * S) end local P = 2.0 * L - Q local Hk = H / 360 local Tr = Hk + 1 / 3 local Tg = Hk local Tb = Hk - 1 / 3 if Tr < 0 then Tr = Tr + 1.0 elseif Tr > 1 then Tr = Tr - 1.0 end if Tg < 0 then Tg = Tg + 1.0 elseif Tg > 1 then Tg = Tg - 1.0 end if Tb < 0 then Tb = Tb + 1.0 elseif Tb > 1 then Tb = Tb - 1.0 end local colorr, colorg, colorb; if Tr < 1 / 6 then colorr = P + ((Q - P) * 6.0 * Tr) elseif 1 / 6 <= Tr and Tr < 1 / 2 then colorr = Q elseif 1 / 2 <= Tr and Tr < 2 / 3 then colorr = P + ((Q - P) * (2 / 3 - Tr) * 6.0) else colorr = P end if Tg < 1 / 6 then colorg = P + ((Q - P) * 6.0 * Tg) elseif 1 / 6 <= Tg and Tg < 1 / 2 then colorg = Q elseif 1 / 2 <= Tg and Tg < 2 / 3 then colorg = P + ((Q - P) * (2 / 3 - Tg) * 6.0) else colorg = P end if Tb < 1 / 6 then colorb = P + ((Q - P) * 6.0 * Tb) elseif 1 / 6 <= Tb and Tb < 1 / 2 then colorb = Q elseif 1 / 2 <= Tb and Tb < 2 / 3 then colorb = P + ((Q - P) * (2 / 3 - Tb) * 6.0) else colorb = P end r = colorr * 255.0 g = colorg * 255.0 b = colorb * 255.0 end r = math.ceil(r) g = math.ceil(g) b = math.ceil(b) return r, g, b end return false end Возврат Возвращает rgb(красный,зелёный,синий) что это ? . [*]Функция: tocolorHSB int, int, int, int tocolorHSB ( float hue [, float saturation = 1.0, float brightness = 1.0, int alpha = 255 ] ) Обязательные аргументы hue: Значение оттенка цвета (0-360). Необязательные аргументы saturation: Значение насыщенности цвета (0-1). brightness: Значение яркость цвета (0-1). alpha: Значение прозрачности цвета (0-255). Возврат Возвращает первое число hex-цвет и ещё три это его составляющие в RGB формате. Код функции function tocolorHSB(hue,saturation,brightness,alpha) if (not saturation) then saturation = 1 end if (not brightness) then brightness = 1 end if (not alpha) then alpha = 255 end local rr,gg,bb = 255,255,255 if (hue <= 60) then rr = 255 gg = math.floor(255*hue/60) bb = 0 elseif (hue <= 120) then rr = math.floor(255*(1 - (hue - 60)/60)) gg = 255 bb = 0 elseif (hue <= 180) then rr = 0 gg = 255 bb = math.floor(255*(hue - 120)/60) elseif (hue <= 240) then rr = 0 gg = math.floor(255*(1 - (hue - 180)/60)) bb = 255 elseif (hue <= 300) then rr = math.floor(255*(hue - 240)/60) gg = 0 bb = 255 else rr = 255 gg = 0 bb = math.floor(255*(1 - (hue - 300)/60)) end rr = rr + (255-rr)*(1-saturation) gg = gg + (255-gg)*(1-saturation) bb = bb + (255-bb)*(1-saturation) rr = rr*brightness gg = gg*brightness bb = bb*brightness local color = tonumber(string.format("0x%02X%02X%02X%02X",alpha,rr,gg,bb)) return color,rr,gg,bb end Автор: Lex128 Прочие функции Функция: getAllWeapons table/bool getAllWeapons( player/ped source,[ bool ammo ] ) ВозвратВозвращает таблицу с оружием и с патронами( если указано в аргументах функции ). function getAllWeapons( source,ammo ) if isElement( source ) then local Table = { } for i = 0,12 do local weap = getPedWeapon ( source, i ) if not ammo then table.insert( Table,weap ) else local ammos = getPedTotalAmmo( source,i ) if ammos > 0 then table.insert( Table, { weap, ammos } ) end end end return Table end return false end Автор: Kenix Функция: getPlayerCount int getPlayerCount () ВозвратВозвращает кол-во игроков. function getPlayerCount( ) return #getElementsByType 'player' end Автор: Kenix Функция: takeMoney bool takeMoney( player thePlayer,int amount) Обязательные аргументы thePlayer:Игрок у кого вы будете брать деньги . amount:Сумма Возврат Возвращает истину если все аргументы были верными. takeMoney = function( player,cash ) if getPlayerMoney ( player ) >= tonumber( cash ) then return takePlayerMoney ( player,cash ) end return false end Автор: Kenix [*]Функция: getWeaponModelFromID getWeaponModelFromID( int id ) Обязательные аргументы id:Идентификатор оружия. Возврат Возвращает модель оружия . function getWeaponModelFromID( id ) if type( id ) == 'number' then local weaponsIds = { --0 слот [1] = 331, --1 слот [2] = 333, [3] = 334, [4] = 335, [5] = 336, [6] = 337, [7] = 338, [8] = 339, [9] = 341, --2 слот [22] = 346, [23] = 347, [24] = 348, --3 слот [25] = 349, [26] = 350, [27] = 351, --4 слот [28] = 352, [29] = 353, [32] = 372, --5 слот [30] = 355, [31] = 356, --6 слот [33] = 357, [34] = 358, --7 слот [35] = 359, [36] = 360, [37] = 361, [38] = 362, --8 слот [16] = 342, [17] = 343, [18] = 344, [39] = 363, --9 слот [41] = 365, [42] = 366, [43] = 367, --10 слот [10] = 321, [11] = 322, [12] = 323, [13] = 324, [14] = 325, [15] = 326, --11 слот [44] = 368, [45] = 369, [46] = 371, --12 слот [40] = 364 } return weaponsIds[ id ] end return false end Автор: Kenix [*]Функция: getWeaponStatFromWeaponID getWeaponStatFromWeaponID( int id ) Обязательные аргументы id:Идентификатор оружия. Возврат Возвращает умение владением оружием. function getWeaponStatFromWeaponID( id ) if type( id ) == 'number' then local t = { -- пистолеты [22] = 69, [23] = 70, [24] = 71, -- дробаны [25] = 72, [26] = 73, [27] = 74, -- пистолеты-пулемёты [28] = 75, [29] = 76, --штурмовые винтовки [30] = 77, [31] = 78, -- винтовки [34] = 79 } return t[ id ] end return false end Автор: Kenix [*]Функция: setRandomMap setRandomMap( ) Внимание! Ресурс mapmanager должен быть запущен. Возврат Возвращает истину если карта успешно поменялась. function setRandomMap( ) local gamemode = exports.mapmanager:getRunningGamemode( ) if gamemode then local array = exports.mapmanager:getMapsCompatibleWithGamemode( gamemode ) if array then local nextmap = array[ math.random(1,#array) ] local change = exports.mapmanager:changeGamemodeMap( nextmap ) if change then return true end return false end return false end return false end Автор: MX_Master [*]Функция: getRandomPlayer element getRandomPlayer( ) Возврат Возвращает случайного игрока. function getRandomPlayer() local players = getElementsByType( "player" ) local pCount = #players return pCount > 0 and players[ math.random( 1, pCount ) ] or false end Автор: DakiLLa [*]Функция: elementRotationToPoint elementRotationToPoint( element el, float x, float y, float z ) Обязательные аргументы el:Элемент x:Ось x y:Ось y z:Ось z Возврат Возвращает истину если поворот элемента оказался успешным. function elementRotationToPoint( el, px, py, pz ) if type( el ) == 'userdata' and isElement( el ) and type( px ) == 'number' and type( py ) == 'number' and type( pz ) == 'number' then local x, y, z, = getElementPosition ( el ) local rotalion = ( 360 - math.deg ( math.atan2 ( ( x - px ), ( y - py ) ) ) ) % 360 return setPedRotation( el, 0, 0, rotalion ) end return false end Автор: Citizen [*]Функция: isRussianText isRussianText( string text ) Обязательные аргументы text:текст Возврат Возвращает истину если текст русский. function isRussianText( text ) if type( text ) == "string" then local len = utfLen( text ) local code = nil for i = 1, len do code = utfCode( utfSub( text, i, i ) ) if code < 1040 or code > 1103 then -- 'А'-'Я' 'а'-'я' if code ~= 1105 and code ~= 1025 then -- 'ё' 'Ё' return false end end end return true end return false end Автор: Fro Классы Небольшой класс по работе с файлами. Стандартные функции MTA + возможность читать файл построчно. File = { new = function( self, filePath ) if self.index then return setmetatable( { }, { __index = self } ) else return setmetatable( { fPath = filePath, buffer = "", index = true }, { __index = File } ) end end, exist = function( self, filePath ) if self.index then if self.fPath then return fileExists( self.fPath ) end return false else return fileExists( filePath ) end end, rename = function( self, filePath, newFilePath ) if self.index then if self.fPath then local res = fileRename( self.fPath, filePath ) self.fPath = filePath return res end return false else return fileRename( filePath, newFilePath ) end end, delete = function( self, filePath ) if self.index then if self.fPath then return fileDelete( self.fPath ) end return false else return fileDelete( filePath ) end end, create = function( self, filePath ) if not self.file then self.fPath = filePath or self.fPath self.file = fileCreate( self.fPath ) return self.file ~= false end return false end, open = function( self, readOnly, filePath ) if not self.file then self.fPath = filePath or self.fPath self.file = fileOpen( self.fPath, readOnly or false ) return self.file ~= false end return false end, close = function( self ) if self.file then local res = fileClose( self.file ) self.file = nil self.buffer = "" return res end return false end, pos = function( self, offset ) if self.file then if offset then return fileSetPos( self.file, offset ) else return fileGetPos( self.file ) end end return false end, size = function( self, filePath ) if self.index then if self.file then return fileGetPos( self.file ) end return false elseif filePath then local hFile = fileOpen( filePath ) if hFile then local fSize = fileGetSize( hFile ) fileClose( hFile ) return fSize end end return false end, flush = function( self ) if self.file then return fileFlush( self.file ) end return false end, write = function( self, string1, ... ) if self.file then return fileWrite( self.file, string1, ... ) end return false end, read = function( self, count ) if self.file then return fileRead( self.file, count ) end return false end, readLine = function( self, count ) if self.file then while true do local endpos = string.find( self.buffer, "\n" ) if not endpos then if fileIsEOF( self.file ) then if self.buffer ~= "" then local line = self.buffer self.buffer = "" return line else return false end end self.buffer = self.buffer .. fileRead( self.file, count or 500 ) else local line = string.sub( self.buffer, 1, endpos - 1 ) self.buffer = string.sub( self.buffer, endpos + 1 ) return line end end end return false end, EOF = function( self ) if self.file then return fileIsEOF( self.file ) end return false end } Пример использования: local file = File:new 'test.txt' file:open( ) local line = nil repeat line = file:readLine( ) if line then print( line ) end until not line file:close( ) Скачать: PastebinАвтор: Fro Библиотека для реализации класса от Lua Dev с обновлением от Kernell и Setuper Если у кого нибудь есть ещё функции или классы или ещё что-то, выкладывайте сюда. Edited March 29, 2014 by Guest 1
MX_Master Posted May 8, 2011 Posted May 8, 2011 пока что все функции - бесполезные, и просмотрите https://wiki.multitheftauto.com/wiki/Useful_Functions
MX_Master Posted May 9, 2011 Posted May 9, 2011 В последнее время очень пригодилась эта функция, т.к. я работаю с таблицами как с объектами класса. Удаляет из таблицы значения по маске индекса. function fRemoveTableFieldsByPattern ( t, sPattern ) if type(t) ~= 'table' or type(sPattern) ~= 'string' then return false end for index, _ in pairs(t) do if string.find( tostring(index), sPattern ) then if type(index) == 'number' then table.remove(t, index) else t[index] = nil end end end return true end Примеры local t = { [123] = 1, [456] = 2, [789] = 3, ["159"] = 4, last = 4 } fRemoveTableFieldsByPattern( t, '^%d+$' ) -- удалить все индексы, состоящие только из цифр -- в таблице t осталось только поле 'last' local t = { ['playerHealth'] = 100, ['playerArmour'] = 0, ['playerMoney'] = 123456, ['onlinePlayersCount'] = 0 } fRemoveTableFieldsByPattern( t, '^player' ) -- удалить все индексы, начинающиеся со слова 'player' -- в таблице t осталось только поле 'onlinePlayersCount' По желанию можно также удалять по маске значения, а не индекса. У меня просто в таблицах некоторые группы полей начинают с одного и того же слова, их много, и вручную каждый раз удалять их - слишком много места в коде.
Lex128 Posted May 23, 2011 Posted May 23, 2011 (edited) Синтаксис int, int, int, int tocolorHSB ( float hue [, float saturation = 1.0, float brightness = 1.0, int alpha = 255 ] ) Обязательные аргументы hue: Значение оттенка цвета (0-360). Необязательные аргументы saturation: Значение насыщенности цвета (0-1). brightness: Значение яркость цвета (0-1). alpha: Значение прозрачности цвета (0-255). Возврат Возвращает первое число hex-цвет и ещё три это его составляющие в RGB формате. Код функции function tocolorHSB(hue,saturation,brightness,alpha) if (not saturation) then saturation = 1 end if (not brightness) then brightness = 1 end if (not alpha) then alpha = 255 end local rr,gg,bb = 255,255,255 if (hue <= 60) then rr = 255 gg = math.floor(255*hue/60) bb = 0 elseif (hue <= 120) then rr = math.floor(255*(1 - (hue - 60)/60)) gg = 255 bb = 0 elseif (hue <= 180) then rr = 0 gg = 255 bb = math.floor(255*(hue - 120)/60) elseif (hue <= 240) then rr = 0 gg = math.floor(255*(1 - (hue - 180)/60)) bb = 255 elseif (hue <= 300) then rr = math.floor(255*(hue - 240)/60) gg = 0 bb = 255 else rr = 255 gg = 0 bb = math.floor(255*(1 - (hue - 300)/60)) end rr = rr + (255-rr)*(1-saturation) gg = gg + (255-gg)*(1-saturation) bb = bb + (255-bb)*(1-saturation) rr = rr*brightness gg = gg*brightness bb = bb*brightness local color = tonumber(string.format("0x%02X%02X%02X%02X",alpha,rr,gg,bb)) return color,rr,gg,bb end Edited May 23, 2011 by Guest
MX_Master Posted May 23, 2011 Posted May 23, 2011 чувачок, это русская ветка форума (: так что английское описание замени на наше
TEDERIs Posted June 22, 2011 Posted June 22, 2011 Синтаксис float math.clamp ( float value, float lower, float upper ) Аргументы value: Значение lower: Нижнее значение upper: Верхнее значение Возврат Возвращает число в пределах lower и upper значений. Код function math.clamp ( value, lower, upper ) if type ( value ) == "number" and type ( lower ) == "number" and type ( upper ) == "number" then if value < lower then value = lower elseif value > upper then value = upper end return value end return false end
Kernell Posted June 22, 2011 Posted June 22, 2011 function math.clamp ( value, lower, upper ) value = tonumber( value ) lower = tonumber( lower ) upper = tonumber( upper ) if value and lower and upper then value = math.min( lower, value ); value = math.max( upper, value ); return value end return false end
Antibird Posted June 23, 2011 Posted June 23, 2011 value = math.min( lower, value ); value = math.max( upper, value ); return value 1. Всегда будет возвращать upper, разве нет? 2. При желании можно еще больше "схлопнуть" код: function math.clamp ( value, lower, upper ) value = tonumber( value ) lower = tonumber( lower ) upper = tonumber( upper ) if value and lower and upper then return value < lower and lower or value > upper and upper or value end return false end 3. А зачем вообще? , когда можно как написано в 6 строчке? Чуточку длиннее по синтаксису, но зато без вызова функции.
Kernell Posted June 23, 2011 Posted June 23, 2011 Действительно косяк.. Ну можно кстати ещё больше "схлопнуть" код: function math.clamp ( value, lower, upper ) value = tonumber( value ); lower = tonumber( lower ); upper = tonumber( upper ); return value and lower and upper and ( value < lower and lower or value > upper and upper or value ) or false; end
Kernell Posted January 4, 2012 Posted January 4, 2012 Функция склонения чисел Синтаксис string math.decl ( int nubmer, string declin1, string declin2, string declin3 ) Код function math.decl( number, declin1, declin2, declin3 ) if number % 10 == 1 and number % 100 ~= 11 then return declin1; elseif number % 10 >= 2 and number % 10 <= 4 and ( number % 100 < 10 or number % 100 >= 20 ) then return declin2; end return declin3; end Пример использования print( "Вы были тут 13 " .. math.decl( 13, 'час', 'часа', 'часов' ) .. ' назад' ); -- Вы были тут 13 часов назад print( "Забанен на 124 " .. math.decl( 124, 'минуту', 'минуты', 'минут' ) ); -- Забанен на 124 минуты
Kenix Posted January 7, 2012 Author Posted January 7, 2012 local label = guiCreateLabel( 0.5,0.5,0.9,0.9,"",true ) guiLabelSetHexColor ( label, "#2e88f9Текст",true )
TwiX! Posted January 7, 2012 Posted January 7, 2012 local label = guiCreateLabel( 0.5,0.5,0.9,0.9,"",true ) guiLabelSetHexColor ( label, "#2e88f9Текст",true ) так работаеть будет? local speclabel = guiCreateLabel(screenWidth/2 - 100, screenHeight - 100, 200, 70, '', false) guiLabelSetHexColor ( speclabel, "Currently spectating:\n" .. getPlayerName(SpectatePlayer),true ) Чтобы ник с цветом был
Kenix Posted January 7, 2012 Author Posted January 7, 2012 Эта функция будет окрашивать весь лейбл в один цвет. Если нужно разные цвета function dxDrawColoredText(str, ax, ay, bx, by, color, scale, font,left,top) left = "left" if not top then top = "top" end local pat = "(.-)#(%x%x%x%x%x%x)" local s, e, cap, col = str:find(pat, 1) local last = 1 while s do if cap == "" and col then color = tocolor(tonumber("0x"..col:sub(1, 2)), tonumber("0x"..col:sub(3, 4)), tonumber("0x"..col:sub(5, 6)), 255) end if s ~= 1 or cap ~= "" then local w = dxGetTextWidth(cap, scale, font) dxDrawText(cap, ax, ay, ax + w, by, color, scale, font,left,top,true) ax = ax + w color = tocolor(tonumber("0x"..col:sub(1, 2)), tonumber("0x"..col:sub(3, 4)), tonumber("0x"..col:sub(5, 6)), 255) end last = e + 1 s, e, cap, col = str:find(pat, last) end if last <= #str then cap = str:sub(last) local w = dxGetTextWidth(cap, scale, font) dxDrawText(cap, ax, ay, ax + w, by, color, scale, font,left,top,true) end end
Fro Posted January 11, 2012 Posted January 11, 2012 Проверка текста на русский язык function isRussianText( text ) local len = utfLen( text ) local code = nil for i = 1, len do code = utfCode( utfSub( text, i, i ) ) if code < 1040 or code > 1103 then -- 'А'-'Я' 'а'-'я' if code ~= 1105 and code ~= 1025 then -- 'ё' 'Ё' return false end end end return true end
Kenix Posted January 11, 2012 Author Posted January 11, 2012 Добавил в пост функцию. Добавил ещё одну новую функцию
Fro Posted February 6, 2012 Posted February 6, 2012 (edited) Небольшой класс по работе с файлами. Стандартные функции MTA + возможность читать файл построково. Скачать: Pastebin Пример использования: local file = File:new( "test.txt" ) file:open( ) --[[while true do local line = file:readLine( ) if not line then break else print( line ) end end]] local line = nil repeat line = file:readLine( ) if line then print( line ) end until not line file:close( ) Edited February 7, 2012 by Guest
Kenix Posted February 6, 2012 Author Posted February 6, 2012 Молодец,Добавил в первый пост. Добавил ещё 5 функций с примерами
Fro Posted February 16, 2012 Posted February 16, 2012 Удаляет пробелы в начале и в конце строки. function string.trim( str ) if type( str ) == "string" then str = string.gsub( str, "^%s*", "" ) str = string.gsub( str, "%s*$", "" ) return str end return false end Обновил класс File: Смотреть
LoveFist Posted February 18, 2012 Posted February 18, 2012 table.serialize - преобразует таблицу в строку (для удобства хранения данных). Функция более совершенна чем table.string поскольку корректно работает с типами данных и вложенными таблицами. Поля содержащие userdata, thread или function игнорируются. string table.serialize(table t) Обязательные аргументы: t - таблица для сериализации Возвращает: строку сериализованной таблицы либо nil table.deserialize - функция обратная сериализации, позволяет получить из строки таблицу table table.deserialize(string s) Обязательные аргументы: s - строка для десериализации Возвращает: таблицу либо nil Pastebin (здесь подсветка кода обрезает '\') Пример: local test = {[1] = 'dw', ['2'] = 123, [3] = {1,2,'ere'}} local tString = table.serialize(test) print(tString)--> {[1] = 'dw', [3] = {[1] = 1, [2] = 2, [3] = 'ere'}, ['2'] = 123} local sTable = table.deserialize(tString) print(sTable[1]..', '..sTable['2'])--> dw, 123
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now