Jump to content

Общий мини "HELP ME" топик по скриптингу


Recommended Posts

Взываю о помощи опытных, подскажите почему это не работает и что поправить?

function createObject (player) 
      local veh = getPedOccupiedVehicle (player) 
      local x, y, z = getElementPosition (player) 
      Object = createObject ( 2002,  x, y, z ) 
      setElementCollisionsEnabled ( Object, false ) 
      attachElements ( Object,  veh, 0.62, 2.25, 0.18) 
end 
  
function recreateObject() 
destroyElement(Object) 
createObject() 
end 
  
createObject() 
setTimer(recreateObject,500,0) 

Link to comment

Не сильно понял логику скрипта, но если вам нужно, чтобы создавался объект приаттаченный к вашему ТС, то это будет выглядеть так:

local Object; 
function createObjectF (player) 
      local veh = getPedOccupiedVehicle (player) 
      local x, y, z = getElementPosition (veh) 
      Object = createObject ( 2002,  x, y, z ) 
      setElementCollisionsEnabled ( Object, false ) 
      attachElements ( Object,  veh, 0.62, 2.25, 0.18) 
end 
addCommandHandler("createobject", createObjectF); 
  
function recreateObjectF() 
    destroyElement(Object) 
end 
addCommandHandler("destroyobject", recreateObjectF); 

Команда "createobject" создает объект и аттачит его к ТС, команда "destroyobject" удаляет объект с вашего ТС.

Link to comment
Не сильно понял логику скрипта, но если вам нужно, чтобы создавался объект приаттаченный к вашему ТС, то это будет выглядеть так:
local Object; 
function createObjectF (player) 
      local veh = getPedOccupiedVehicle (player) 
      local x, y, z = getElementPosition (veh) 
      Object = createObject ( 2002,  x, y, z ) 
      setElementCollisionsEnabled ( Object, false ) 
      attachElements ( Object,  veh, 0.62, 2.25, 0.18) 
end 
addCommandHandler("createobject", createObjectF); 
  
function recreateObjectF() 
    destroyElement(Object) 
end 
addCommandHandler("destroyobject", recreateObjectF); 

Команда "createobject" создает объект и аттачит его к ТС, команда "destroyobject" удаляет объект с вашего ТС.

Спасибо за ответ, объект не только должен быть аттачен но и появляться/исчезать без остановки согласно таймеру. Что только не пробовал, объект либо просто создается один раз, либо получаю кучу ошибок в дебаг

Link to comment
local Object, timer1, x, y, z; 
function createObjectF (player) 
      local veh = getPedOccupiedVehicle (player) 
      x, y, z = getElementPosition (veh) 
      timer1 = setTimer(function() Object = createObject ( 2002,  x, y, z ); setElementCollisionsEnabled ( Object, false ); attachElements ( Object,  veh, 0.62, 2.25, 0.18); setTimer(function() destroyElement(Object) end, 100, 1) end, 500, 0); 
end 
addCommandHandler("createobject", createObjectF); 
  
function recreateObjectF() 
    destroyElement(Object); 
    killTimer(timer1); 
end 
addCommandHandler("destroyobject", recreateObjectF); 

Тогда вот так.

Link to comment

Некак

Тебе нужно написать свою GUI библиотеку.

Ну а вообще как вариант это получать позицию gui элемента и обновлять позицию dxDrawImage по этим координатам + оффсет в рендере.

Link to comment

Тогда вот так.

Спасибо огромное, это работает! Начинаю по-тихоньку понимать логику =)

Вот готовый код (объект 2000 это из ресурса ParticlеObjects, а именно CamFlash)

Получились очень забавные стробоскопы ))

on = 0 
function checkModel( theVehicle ) 
Car = getElementModel ( theVehicle ) 
end 
addEventHandler ( "onPlayerVehicleEnter", getRootElement(), checkModel ) 
function onEnterVehicle ( theVehicle, seat, jacked ) 
if ( getElementModel ( theVehicle ) == 598 ) then 
bindKey ( source, "F12", "down", createStrab ) 
end 
end 
  
local Object, timer1, x, y, z; 
function createStrab ( player ) 
   if Car == 598 then 
      if on == 0 then 
      on = 1   
      local veh = getPedOccupiedVehicle (player) 
      x, y, z = getElementPosition (veh) 
  
      timer1 = setTimer(function()  
      Object1 = createObject ( 2000,  x, y, z );  
      setElementCollisionsEnabled ( Object1, false );  
      attachElements ( Object1,  veh, 0.555, 2.4, 0.08); 
      setTimer(function() destroyElement(Object1) end, 100, 1)  
      end, 500, 0); 
  
      timer2 = setTimer(function()  
      Object2 = createObject ( 2000,  x, y, z );  
      setElementCollisionsEnabled ( Object2, false );  
      attachElements ( Object2,  veh, 0.555, 2.4, 0.08); 
      setTimer(function() destroyElement(Object2) end, 100, 1)  
      end, 600, 0); 
  
      timer3 = setTimer(function()  
      Object3 = createObject ( 2000,  x, y, z );  
      setElementCollisionsEnabled ( Object3, false );  
      attachElements ( Object3,  veh, -0.555, 2.4, 0.08); 
      setTimer(function() destroyElement(Object3) end, 100, 1)  
      end, 550, 0); 
  
      timer4 = setTimer(function()  
      Object4 = createObject ( 2000,  x, y, z );  
      setElementCollisionsEnabled ( Object4, false );  
      attachElements ( Object4,  veh, -0.555, 2.4, 0.08); 
      setTimer(function() destroyElement(Object4) end, 100, 1)  
      end, 650, 0); 
  
      else 
      on=0 
  
---      destroyElement(Object1); 
---      destroyElement(Object2); 
---      destroyElement(Object3); 
---      destroyElement(Object4); 
      killTimer(timer1); 
      killTimer(timer2); 
      killTimer(timer3); 
      killTimer(timer4); 
  
      end 
   end 
end 
  
function destroyStrab() 
---destroyElement(Object1); 
---destroyElement(Object2); 
---destroyElement(Object3); 
---destroyElement(Object4); 
killTimer(timer1); 
killTimer(timer2); 
killTimer(timer3); 
killTimer(timer4); 
end 
addEventHandler ( "onVehicleExplode", getRootElement(), destroyStrab ) 
function onExitVehicle ( theVehicle, seat, jacked ) 
if ( getElementModel ( theVehicle ) == 598 ) then 
unbindKey ( source, "F12", "down", createStrab ) 
if on == 1 then 
---destroyElement(Object1); 
---destroyElement(Object2); 
---destroyElement(Object3); 
---destroyElement(Object4); 
killTimer(timer1); 
killTimer(timer2); 
killTimer(timer3); 
killTimer(timer4); 
end 
end 
end 
addEventHandler ( "onPlayerVehicleExit", getRootElement(), onExitVehicle ) 
addEventHandler ( "onPlayerVehicleEnter", getRootElement(), onEnterVehicle ) 

Теперь у меня появилась новая забавная идея и снова у меня пара вопросов )

вот код

on = 0 
function checkModel( theVehicle ) 
Car = getElementModel ( theVehicle ) 
end 
addEventHandler ( "onPlayerVehicleEnter", getRootElement(), checkModel ) 
  
function onEnterVehicle ( theVehicle, seat, jacked ) 
if ( getElementModel ( theVehicle ) == 598 ) then 
bindKey ( source, "u", "down", createObject ) 
end 
end 
addEventHandler ( "onPlayerVehicleEnter", getRootElement(), onEnterVehicle ) 
  
function createOblect ( player ) 
   if Car == 598 then 
      if on == 0 then 
      on = 1   
      local veh = getPedOccupiedVehicle (player) 
      x, y, z = getElementPosition (veh) 
      object = createObject ( 1973,  x, y, z ) 
      attachElements ( object,  veh, 0, 0, 3) 
      else 
      on=0 
      destroyElement(object) 
      end 
   end 
end 
  
function onBind () 
bindKey ( source, "n", "down", move ) 
end 
addEventHandler ( "onPlayerVehicleEnter", getRootElement(), onBind ) 
  
function offBind () 
unbindKey ( source, "n", "down", move ) 
end 
addEventHandler ( "onPlayerVehicleExit", getRootElement(), offBind ) 
  
function move() 
moveObject (object, 1000, 1, 0, 3) 
end 
  

Идея скрипта в том чтобы в момент когда персонаж садится в авто, к авто аттачился объект, и этот объект двигался относительно авто по кнопке. У меня не получилось сделать чтобы объект аттачился сразу при посадке (без кнопки), и вместо того чтобы двигаться он исчезает.. Очень прошу направьте на путь истинный )

Link to comment

такой вопрос, каким образом вставить текст или фото в пространство в одностороннем обзоре ее(его) игроком, к примеру на любую из стен ?

Link to comment
Создайте таблицу { группа = { цвет блипа }, ... } это существенно сократит размер кода и будет понятнее, что Вы просите.
    sortGC = {  
        Admin = {137, 0, 255},  
        SuperModerator = {255, 96, 0},  
        Helper = {0, 128, 255},  
        Garant = {255, 128, 0},  
        Security = {0, 51, 255},  
        DT = {255, 0, 0},  
        Donate = {255, 213, 0},  
        Everyone = {255, 222, 0} 
        } 
  
    local theplayerblip = getBlipAttachedTo(source) 
    local blips = getElementsByType ( "blip" ) 
    for blipK, blipV in ipairs ( blips ) do 
    if getElementAttachedTo( blipV ) == thePlayer then 
        if isObjectInACLGroup ( "user." .. getAccountName ( getPlayerAccount ( source )), aclGetGroup ( "#" ) ) then 
            setPlayerNametagColor (source, #) 
            setBlipColor (theplayerblip, #, 255) 
        end 
    end 

Как применить данную таблицу в коде теперь? И видно, что цвет блипа устанавливается для всех. Как установить индивидуальность?

Link to comment

Приветствую парни столкнулся с проблемой расхождения времени клиента и сервера из-за чего бывает такое что вещи в инвентаре двоятся (не DayZ) сервер работает на переписанном Valhalla mod не плохо работает но эта ошибка мешает самой работе сервера.Как это исправить подскажите?

Link to comment
Приветствую парни столкнулся с проблемой расхождения времени клиента и сервера из-за чего бывает такое что вещи в инвентаре двоятся (не DayZ) сервер работает на переписанном Valhalla mod не плохо работает но эта ошибка мешает самой работе сервера.Как это исправить подскажите?

Наверное потому, что getRealTime() на сервере, возвращает время сервера, а getRealTime() на клиенте возвращает время клиента. Как вариант, все операции со временем выполняй на стороне сервера. Если не хочешь, то просто когда trigger'ишь на клиент, передавай в качестве параметра реальное время (но это очень плохое решение).

Link to comment
Приветствую парни столкнулся с проблемой расхождения времени клиента и сервера

Проблема? По моему это очевидные вещи, либо вы не понимаете, что клиентские скрипты выполняются на самом клиенте (клиент - это игрок который играет на вашем сервере, его компьютер!), а серверные - на сервере соответственно (опять же очевидные вещи). Логично что у клиента будет другое время, даже если они будут находиться в одинаковых часовых поясах. Исправить такие вещи никак нельзя - это логическая ошибка, вы не правильно продумали логику.

Link to comment
local isLightOn = false 
-- don't mess with the tables
local flashlight = {}
local light_shader = {}
local shader_jaroovka = {}
local shader_rays = {}
local shader_null = {}
local isFlon = {}  -- a list of players with fl turned on (for local client)
local isFLen = {}  -- a list of players with fl enabled (for local client)
local fLInID = {}  -- a list fl of inerior ID (for local client)
local lightNumber = 0
 
-- Below this line you can edit as You wish
 
local isSynced = true -- disable if you want to disable light effect synchro (only localPlayer's flashlight effect remains)
local maxLights = 1 -- how many light effects can be streamed in at once (besides localPlayer's)
local alterAttach = false -- true=attaches the flashlight to ..head (it seems to be the best place and it works)
local disableFLTex = false -- true=makes the flashlight body not visible (useful for alter attach)
local autoEnableFL = false -- true=the player gets the flashlight without writing commands
 
local switch_key = 'r' -- define the key that switches the light effect
local lightColor = {1,1,0.7,0.7} -- rgba color of the projected light, light rays and the lightbulb
local effectRange = 50 -- effect max distance 120
local isFakeBump = false -- apply fake bumps to the light texture
local isLightDir=true -- the vertexes oposite to the lightsource will NOT be affected (turn off for custom maps !!)
local lightDirAcc = 0.2 -- the accuracy of the above (0.01-1)
local maxEffectSwitch=60 -- max distance between camera and player coords form which the effect is switched off
local DistFade = {110, 80, 49, 1} -- [0]MaxEffectFade,[1]MinEffectFade,[2]MaxFlashFade,[3]MinFlashFade
local objID = 15060  -- the object we are going to replace (interior building shadow in this case)
local theTikGap = 0.8 -- here you set how many seconds to wait after switching the flashlight on/off
 
local getLastTick = getTickCount ( )-(theTikGap*1000)
local shader_null = dxCreateShader ( "shaders/shader_null.fx",0,0,false )
local textureCube = dxCreateTexture ( "textures/cubebox.dds")
 
---------------------------------------------------------------------------------------------------
local removeList = {
                        "",                                             -- unnamed
                        "basketball2","skybox_tex", "drvin_screen",     -- other
                        "flashlight*","crackedground*",             -- other
                        "roughcornerstone*",                        -- other
                        "fireba*",                      -- fire
                        "muzzle_texture*",                  -- gunshots
                        "font*","radar*",                   -- hud
                        "*headlight*",                      -- vehicles
                        "*shad*",                       -- shadows
                        "coronastar","coronamoon","coronaringa",        -- coronas
                        "lunar",                        -- moon
                        "tx*",                          -- grass effect
                        "lod*",                         -- lod models
                        "cj_w_grad",                        -- checkpoint texture
                        "*cloud*",                      -- clouds
                        "*smoke*",                      -- smoke
                        "sphere_cj",                        -- nitro heat haze mask
                        "particle*",                        -- particle skid and maybe others
                        "water*","sw_sand", "coral",                -- sea
                        "boatwake*","splash_up","carsplash_*",          -- splash
                        "gensplash","wjet4","bubbles",              -- splash
                        "blood*",                       -- blood
 
                    }
 
---------------------------------------------------------------------------------------------------
--Updates light positions and rotation of the light direction
function renderLight()
for index,thisPed in ipairs(getElementsByType("player")) do
    if light_shader[thisPed] then
        xx1, yy1, zz1, lxx1, lyy1, lzz1,rl = getCameraMatrix()
         if (alterAttach) then
            x1, y1, z1 = getPedBonePosition ( thisPed, 5 )
            lx1, ly1, lz1 = getPedBonePosition ( thisPed, 8 )
 
            local yaw = math.atan2(lx1-x1,ly1-y1)
            yaw = yaw-math.rad(7)
            local pitch = (math.atan2(lz1-z1, math.sqrt(((lx1-x1) * (lx1-x1)) + ((ly1-y1) * (ly1-y1)))))
            pitch = pitch - math.rad(20)
            local roll = 0
            local movx=xx1-x1
            local movy=yy1-y1
            local movz=zz1-z1      
       
            dxSetShaderValue ( light_shader[thisPed],"rotate",yaw,roll,pitch)  
            dxSetShaderValue(light_shader[thisPed],"alterPosition",movx,movy,movz)
         else
            x1, y1, z1 = getPedBonePosition ( thisPed, 24 )
            lx1, ly1, lz1 = getPedBonePosition ( thisPed, 25 )
 
            local yaw = math.atan2(lx1-x1,ly1-y1)
            local pitch = (math.atan2(lz1-z1, math.sqrt(((lx1-x1) * (lx1-x1)) + ((ly1-y1) * (ly1-y1)))))
            local roll = 0
            local movx=xx1-x1
            local movy=yy1-y1
            local movz=zz1-z1      
       
            dxSetShaderValue ( light_shader[thisPed],"rotate",yaw,roll,pitch)  
            dxSetShaderValue(light_shader[thisPed],"alterPosition",movx,movy,movz)
         end
        end                                        
    end
end
 
---------------------------------------------------------------------------------------------------
 
function createFlashlightModel(thisPed)
 
if not flashlight[thisPed] then
    flashlight[thisPed] = createObject(objID,0,0,0,0,0,0,true)
    if disableFLTex and shader_null then
        engineApplyShaderToWorldTexture ( shader_null, "flashlight_COLOR", flashlight[thisPed] )    
        engineApplyShaderToWorldTexture ( shader_null, "flashlight_L", flashlight[thisPed] )    
    end
    setElementAlpha(flashlight[thisPed],254)
    if (alterAttach) then
        exports.bone_attach:attachElementToBone(flashlight[thisPed],thisPed,1,0,0.025,0.09,-100,0,0)
        else
        exports.bone_attach:attachElementToBone(flashlight[thisPed],thisPed,12,0,0.015,0.2,0,0,0)
        end
    end
end
 
function destroyFlashlightModel(thisPed)
if flashlight[thisPed] then        
    exports.bone_attach:detachElementFromBone(flashlight[thisPed])
    if disableFLTex and shader_null then
        engineRemoveShaderFromWorldTexture ( shader_null, "*", flashlight[thisPed] )
    end
    destroyElement(flashlight[thisPed])
    flashlight[thisPed]=nil
    end
end
 
---------------------------------------------------------------------------------------------------
 
function createWorldLightShader(thisPed)
if light_shader[thisPed] or ((isSynced==false) and (thisPed~=localPlayer)) then return end
if (thisPed~=localPlayer) then lightNumber = lightNumber + 1 end
 
    light_shader[thisPed] = dxCreateShader ( "shaders/shader_light.fx",1,effectRange,true,"world,object,vehicle,ped")
    if not light_shader[thisPed] then return end
    dxSetShaderValue ( light_shader[thisPed],"sCubeTexture", textureCube )
    dxSetShaderValue ( light_shader[thisPed],"isLightDir", isLightDir )
    dxSetShaderValue ( light_shader[thisPed],"isFakeBump", isFakeBump )
    dxSetShaderValue ( light_shader[thisPed],"lightColor",lightColor)
    dxSetShaderValue ( light_shader[thisPed],"lightDirAcc", lightDirAcc )
    dxSetShaderValue ( light_shader[thisPed],"DistFade",DistFade)
    engineApplyShaderToWorldTexture ( light_shader[thisPed], "*" )
 
    -- remove light effect from the texture list
    for _,removeMatch in ipairs(removeList) do
        engineRemoveShaderFromWorldTexture ( light_shader[thisPed], removeMatch )  
        end
    -- lazy re-apply list
    engineApplyShaderToWorldTexture ( light_shader[thisPed], "ws_tunnelwall2smoked" )
    engineApplyShaderToWorldTexture ( light_shader[thisPed], "shadover_law" )
    engineApplyShaderToWorldTexture ( light_shader[thisPed], "greenshade_64" )
end
 
function destroyWorldLightShader(thisPed)
if light_shader[thisPed] then
if (thisPed~=localPlayer) then lightNumber = lightNumber - 1 end
    engineRemoveShaderFromWorldTexture ( light_shader[thisPed], "*" )
    destroyElement ( light_shader[thisPed] )
    light_shader[thisPed]=nil
    end
end
 
---------------------------------------------------------------------------------------------------
 
function createFlashLightShader(thisPed)
if not flashlight[thisPed] then return false end
if not shader_jaroovka[thisPed] or shader_rays[thisPed] then
    shader_jaroovka[thisPed]=dxCreateShader("shaders/shader_jaroovka.fx",1,0,false)
    shader_rays[thisPed]=dxCreateShader("shaders/flash_light_rays.fx",1,0,true)
    if not shader_jaroovka[thisPed] or not shader_rays[thisPed] then
        outputChatBox( "Could not create shader. Please use debugscript 3" )
    end    
    engineApplyShaderToWorldTexture ( shader_jaroovka[thisPed],"flashlight_L", flashlight[thisPed] )
    engineApplyShaderToWorldTexture ( shader_rays[thisPed], "flashlight_R", flashlight[thisPed] )  
    dxSetShaderValue (shader_jaroovka[thisPed],"lightColor",lightColor)
    dxSetShaderValue (shader_rays[thisPed],"lightColor",lightColor)
    end
end
 
function destroyFlashLightShader(thisPed)
if shader_jaroovka[thisPed] or shader_rays[thisPed] then
    destroyElement(shader_jaroovka[thisPed])
    destroyElement(shader_rays[thisPed])
    shader_jaroovka[thisPed]=nil
    shader_rays[thisPed]=nil
    end
end
 
---------------------------------------------------------------------------------------------------
 
function playSwitchSound(this_player)
pos_x,pos_y,pos_z=getElementPosition (this_player)
local flSound = playSound3D("sounds/switch.wav", pos_x, pos_y, pos_z, false)
setSoundMaxDistance(flSound,40)
setSoundVolume(flSound,0.6)
end
 
function flashLightEnable(isEN,this_player)
if isEN==true then
        isFLen[this_player]=isEN    
    else
        isFLen[this_player]=isEN    
    end
end
 
function flashLightSwitch(isON,this_player)
if isElementStreamedIn(this_player) and isFLen[this_player] then  playSwitchSound(this_player) end
if isON then
        isFlon[this_player]=true
    else
        isFlon[this_player]=false
    end
end
 
 
function whenPlayerQuits(this_player)
destroyWorldLightShader(this_player)
destroyFlashlightModel(this_player)
destroyFlashLightShader(this_player)  
end
 
---------------------------------------------------------------------------------------------------
-- streamig in/out the light effect
 
function streamInAndOutFlEffects()
for index,this_player in ipairs(getElementsByType("player")) do
    local cam_x, cam_y, cam_z, _, _, _ = getCameraMatrix()
    local player_x,player_y,player_z = getElementPosition(this_player)
    --outputChatBox(isFlon[this_player])
    local getDist = getDistanceBetweenPoints3D(cam_x,cam_y,cam_z,player_x,player_y,player_z)
    if  isElementStreamedIn(this_player) and getDist<=maxEffectSwitch then
   
        if (not light_shader[this_player]) and (isFlon[this_player]==true) then
            if ((lightNumber<=maxLights) or (this_player==localPlayer)) then
                createWorldLightShader(this_player)
            end
        end
        if light_shader[this_player] and isFlon[this_player]==false then    
        destroyWorldLightShader(this_player)    
        end
    end
    if (not isElementStreamedIn(this_player) or getDist>maxEffectSwitch) and light_shader[this_player] and isFlon[this_player]==true then
        destroyWorldLightShader(this_player)        
        end
    end
--outputChatBox(lightNumber.." of "..maxLights)
end
 
Link to comment

Мб может кто то поделится кодом, чтобы находить совпадения с guiEdti'a и gridlist'om? Ну тоесть имеется огромный список карт и нужно сделать поиск, чтобы все не перебирать.

Link to comment

Могу только подсказать способ реализации.

local players = getElementsByType("player") 
local theplayer = {} 
Очищаем сам список Table.clear() 
foreach(players in v) 
{ 
if(string.regex("Тут ваше регулярное выражение", getPlayerName ( v) ) 
{ 
Если совпало добавляем в таблицу 
table.insert(theplayer, v) 
} 
} 

Потом выводишь все в свой grid

Link to comment
Могу только подсказать способ реализации.
local players = getElementsByType("player") 
local theplayer = {} 
Очищаем сам список Table.clear() 
foreach(players in v) 
{ 
if(string.regex("Тут ваше регулярное выражение", getPlayerName ( v) ) 
{ 
Если совпало добавляем в таблицу 
table.insert(theplayer, v) 
} 
} 

Потом выводишь все в свой grid

Ужас...

Пусть вы и смешали несколько языков в один, но не ужели так сложно расставить отступы, и просто соблюдать чистоту кода? Я понимаю, вы с своих проектах кучу говна разводите и не задумываетесь о последствиях, но вы задумайтесь о тех кто этот код будет читать. Тут уже много раз поднимался разговор об этом, даже есть целая тема посвящённая этой проблеме.

Link to comment

> но не ужели так сложно расставить отступы

Кнопочка таб здесь не рабит)

> Я понимаю, вы с своих проектах кучу говна разводите и не задумываетесь о последствиях

function createPlayerList (parent) 
    --Поиск по части имени 
    local findbutton = guiCreateButton( 0.23, 0.03, 0.08, 0.07, "Искать", true, parent) 
    findbox = guiCreateEdit( 0.02, 0.03, 0.2, 0.07, "", true, parent) 
    addEventHandler ( "onClientGUIClick", findbutton, FindPlayers, false ) 
    --Create the grid list element 
    playerList = guiCreateGridList ( 0.02, 0.13, 0.30, 0.8, true, parent ) 
    addEventHandler ( "onClientGUIClick", playerList, SelectedPlayer, false ) 
  
    --Create a players column in the list 
    local column = guiGridListAddColumn( playerList, "Player", 0.85 ) 
    if ( column ) then --If the column has been created, fill it with players 
        for id, player in ipairs(getElementsByType("player")) do 
            local row = guiGridListAddRow ( playerList ) 
            guiGridListSetItemText ( playerList, row, column, getPlayerName ( player ), false, false ) 
        end 
    end 
end 
Или тот же MYSQL 
function single_query(query) 
    if(modules == 1) then 
        local result = mysql_query(handler, query) 
        if (not result) then 
            outputDebugString("Error executing the query: (" .. mysql_errno(handler) .. ") " .. mysql_error(handler)) 
            return false 
        else 
            mysql_free_result(result) -- Freeing the result is IMPORTANT 
            return true 
        end 
    else 
        local result = dbExec( handler, query) 
        if (not result) then 
            outputDebugString("Error executing the query: (" .. query .. ")" ) 
            return false 
        else 
            return true 
        end 
    end 
end 
  

Если это по вашему гавно, то извольте.

> Тут уже много раз поднимался разговор об этом, даже есть целая тема посвящённая этой проблеме.

Повторюсь язык LUA он не по мне, а так как вариантов нет делаю как мне удобней.

Link to comment
Повторюсь язык LUA он не по мне, а так как вариантов нет делаю как мне удобней.

Во-первых: не LUA, а Lua.

http://www.lua.org/about.html

"Lua" (pronounced LOO-ah) means "Moon" in Portuguese. As such, it is neither an acronym nor an abbreviation, but a noun. More specifically, "Lua" is a name, the name of the Earth's moon and the name of the language. Like most names, it should be written in lower case with an initial capital, that is, "Lua". Please do not write it as "LUA", which is both ugly and confusing, because then it becomes an acronym with different meanings for different people. So, please, write "Lua" right!

Во-вторых: Я тоже много раз говорил о том, что не люблю Lua и любые не Си-подобные языки. Но причём тут вы вобще? Вы не себе помогаете, а другим, тут есть люди которые любят этот язык, не будьте таким эгоистом!

Если это по вашему гавно, то извольте.

Именно.

Код не имеет понятной структуры, просто куча кода. Непонятно зачем скобки в if ... then. Единого стиля кода тоже нет, то вы ставите пробелы между операторами, то не ставите. Вобще всё как попало. Если вы думаете, что я придираюсь, то почитайте стандарты оформления кода разных компаний. На всеми любимом хабре этот вопрос конечно же постоянно поднимается. Вот список стандартов: http://habrahabr.ru/post/38214/

P.S. Используйте пробелы вместо TAB на форуме

Link to comment

Не пишется текст в БД.

Вот так пишет:

mysql_query ( dbConnection, "INSERT INTO houses (owner) VALUES (123)" ) 

Вот так не пишет:

mysql_query ( dbConnection, "INSERT INTO houses (owner) VALUES (asdzxccccqq)" ) 

Типа столбца: varchar(30), сравнение: utf8_bin

Kenix помог, проблема решена.

Link to comment

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...