Lua error unexpected symbol near

Attempt to call a nil value

Attempt to call a nil value

Description: calling a function that doesn’t exist

printtt(«abc») — printtt is not a function

test() — calling before it’s defined, same error

Unexpected symbol near ‘something’

Description: an invalid character is placed next to a value/keyword/variable/function call

function abc()) end — unexpected symbol near ‘)’

a l= 15 — unexpected symbol near ‘l’

local a = 5] — unexpected symbol near ‘]’

Attempt to index global ‘variable’ (a nil value)

Description: indexing via [key] or .key for a variable that doesn’t exist

abc.x = 5 — abc is nil, error

abc = {} — abc defined here

xyz[‘x’] = ‘abc’ — xyz is nil, error

Attempt to perform arithmetic on a nil value

Description: performing arithmetic (*, /, -, +, %, ^) on a nil value

print(xyz + 5) — error, xyz not defined

a = a + 5 — error, a not defined

Attempt to perform arithmetic on field ‘?’ (a nil value)

Description: performing arithmetic (*, /, -, +, %, ^) on a nil value

Attempt to compare nil with <TYPE>

Description: using a comparison operator (<, >, ~=, ==, >=, <=) in which one side is a nil value

print(x < y) — y is not defined

Malformed number near <NUMBER>

Description: the number has an invalid character next to it

print(12345aaa) — aaa makes it a malformed number

Unfinished capture | Malformed pattern

Description: the pattern is missing a closing ), or a closing ]

print(string.match(‘ABC’, ‘(‘)) — unfinished capture

print(string.match(‘ABC’, ‘[‘)) — malformed pattern

When you get an error, Lua provides a stack trace showing you where it originates from, where the error occurs, the function calls that led to the error, and the line number of where it occurred.

A general error will look like this:

file_location:LINE NUMBER: error message

file_location:LINE NUMBER: in <local/function> ‘FUNC’

file_location:LINE NUMBER: in main chunk

C:Usersuserlua_file.lua:5: attempt to perform arithmetic on a nil value (field ‘x’)

C:Usersuserlua_file.lua:5: in local ‘c’

C:Usersuserlua_file.lua:7: in local ‘b’

C:Usersuserlua_file.lua:9: in function ‘a’

C:Usersuserlua_file.lua:12: in main chunk

The code that resulted in this error is:

Here you can see the line number 5 after the file location, which tells us where the exact line with the code that resulted in the error. The stack traceback shows the functions that were called that led up to that.

First, function a is called at line 12, then function b is called at line 9 inside of a, then c is called at line 7 inside of function b, and finally at line 5, the error occurs inside of function c.

A note to add is that comments can offset the line number and make it appear as the error is in a line that doesn’t exist or doesn’t look like an error,

Нашел админ-хелпер для сампа, решил переписать под другой сервер, выходит ошибка, не могу найти где именно. Помогите!

 Где «******», это убрал название форума, дабы не было рекламы.

script_name('Admin-Helper')

require 'lib.sampfuncs'
require 'lib.moonloader'
local inicfg = require 'inicfg'
local q = require 'lib.samp.events'
local encoding = require 'encoding'
local requests = require 'requests'
local lanes = require('lanes').configure()
local key = require 'vkeys'
 
 
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
sampAddChatMessage("{CECECE}[{FF6600}Admin-Helper{CECECE}] Скрипт успешно загружен. Разработчик: Shanzix", 0xCECECE)
    while true do
wait(0)
if not sampIsChatInputActive() then
    if wasKeyPressed(key.VK_MULTIPLY) then
    sampSetChatInputText("/a ")
sampSetChatInputEnabled(true)
    end
if wasKeyPressed(key.VK_F2) then
    sampSetChatInputText("/pm ")
sampSetChatInputEnabled(true)
    end
 
if not sampIsDialogActive() then
     if wasKeyPressed(key.VK_F3) then
     sampShowDialog(1004, "{ffcc00}Введи ID получателя сообщения", "{FFFFFF}/pm [ID] Игрок на нарушает/Игрок наказан.", "Не наруш.", "Наказан", 1)
end
result, button, list, input = sampHasDialogRespond(1004)
if result then
     if button == 1 then
     sampSendChat(string.format("/pm %s Не наблюдаю нарушений от игрока. Приятной игры!)", input))
     else
     sampSendChat(string.format("/pm %s Игрок наказан. Приятной игры на нашем сервере!)", input))
     end
end
 
if isKeyDown(key.VK_MENU) and isKeyJustPressed(key.VK_1) then
     sampShowDialog(1000, "{ffcc00}Введи ID получателя сообщения", "{FFFFFF}/pm [ID] Читайте всю информацию на форуме проекта, [*********].", "Отправить", "Отмена", 1)
end
result, button, list, input = sampHasDialogRespond(1000)
if result then
     if button == 1 then
     sampSendChat(string.format("/pm %s Читайте всю информацию на форуме проекта, *******.", input))
end
end
 
if isKeyDown(key.VK_MENU) and isKeyJustPressed(key.VK_2) then
     sampShowDialog(1001, "{ffcc00}Введи ID получателя сообщения", "{FFFFFF}/pm [ID] Пишите жалобу на форум ******** с доказательствами.", "Отправить", "Отмена", 1)
end
result, button, list, input = sampHasDialogRespond(1001)
if result then
     if button == 1 then
     sampSendChat(string.format("/pm %s Пишите жалобу на форум [*******] с доказательствами.", input))
end
end
 
if isKeyDown(key.VK_MENU) and isKeyJustPressed(key.VK_3) then 
     sampShowDialog(1002, "{ffcc00}Введи ID получателя сообщения", "{FFFFFF}/pm [ID] Ваш ник можно сменить только за деньги [/mm - донат рубли].", "Отправить", "Отмена", 1)
end
result, button, list, input = sampHasDialogRespond(1002)
if result then
     if button == 1 then
     sampSendChat(string.format("/pm %s Ваш ник можно сменить только за деньги [/mm - донат рубли].", input))
end
end
 
if wasKeyPressed(key.VK_NUMPAD0) then
sampShowDialog(1003, "{ffcc00}Введи ID получателя сообщения", "{FFFFFF}/pm [ID] Shanzix желает Вам приятной игры на нашей сервер!", "Отправить", "Отмена", 1)
end
result, button, list, input = sampHasDialogRespond(1003)
if result then
if button == 1 then
sampSendChat(string.format("/pm %s Shanzix желает Вам приятной игры на нашей сервер!", input))
end
end
 
if isKeyDown(key.VK_MENU) and isKeyJustPressed(key.VK_4) then
sampShowDialog(1005, "{ffcc00}Введи ID получателя сообщения", "{FFFFFF}/pm [ID] Промокод можно ввести с любого уровня [/mm - 9].", "Отправить", "Отмена", 1)
end
result, button, list, input = sampHasDialogRespond(1005)
if result then
if button == 1 then
sampSendChat(string.format("/pm %s Промокод можно ввести с любого уровня [/mm - 9].", input))
end
end
 
if isKeyDown(key.VK_MENU) and isKeyJustPressed(key.VK_5) then
sampShowDialog(1006, "{ffcc00}Введи ID получателя сообщения", "{FFFFFF}/pm [ID] Промокоды на нашем сервере: «#McLine» и «#ЧЕРКЕС»", "Отправить", "Отмена", 1)
end
result, button, list, input = sampHasDialogRespond(1006)
if result then
if button == 1 then
sampSendChat(string.format("/pm %s Промокоды на нашем сервере: «#McLine» и «#ЧЕРКЕС»", input))
end
end
 
if isKeyDown(key.VK_MENU) and isKeyJustPressed(key.VK_6) then
sampShowDialog(1007, "{ffcc00}Введи ID получателя сообщения", "{FFFFFF}/pm [ID] Работаю по вашей жалобе | Приятной игры!"), "Отправить", "Отмена", 1)
end
result, button, list, input = sampHasDialogRespond(1007)
if result then
if button == 1 then
sampSendChat(string.format("/pm %s Работаю по вашей жалобе | Приятной игры!", input))
end
end
 
if wasKeyPressed(key.VK_DIVIDE) then
sampSetChatInputText("/st ")
sampSetChatInputEnabled(true)
end
if isKeyDown(key.VK_MENU) and wasKeyPressed(key.VK_DIVIDE) then
sampSetChatInputText("/offst ")
sampSetChatInputEnabled(true)
end
if wasKeyPressed(key.VK_DECIMAL) then
sampSetChatInputText("/re ")
sampSetChatInputEnabled(true)
end
if wasKeyPressed(109) then
sampSetChatInputText("/goto ")
sampSetChatInputEnabled(true)
end
if wasKeyPressed(107) then
sampSetChatInputText("/gethere ")
sampSetChatInputEnabled(true)
end
if wasKeyPressed(key.VK_NUMPAD1) then
sampSetChatInputText("/kick ")
sampSetChatInputEnabled(true)
end
if wasKeyPressed(key.VK_NUMPAD3) then
sampSetChatInputText("/mute ")
sampSetChatInputEnabled(true)
end
if isKeyDown(key.VK_MENU) and wasKeyPressed(key.VK_NUMPAD3) then
sampSetChatInputText("/offmute ")
sampSetChatInputEnabled(true)
end
if isKeyDown(key.VK_CONTROL) and wasKeyPressed(key.VK_NUMPAD3) then
sampSetChatInputText("/unmute ")
sampSetChatInputEnabled(true)
end
if wasKeyPressed(key.VK_NUMPAD5) then
sampSetChatInputText("/prison ")
sampSetChatInputEnabled(true)
end
if isKeyDown(key.VK_CONTROL) and wasKeyPressed(key.VK_NUMPAD5) then
sampSetChatInputText("/unprison ")
sampSetChatInputEnabled(true)
end
if wasKeyPressed(key.VK_NUMPAD7) then
sampSetChatInputText("/warn ")
sampSetChatInputEnabled(true)
end
if isKeyDown(key.VK_MENU) and wasKeyPressed(key.VK_NUMPAD7) then
sampSetChatInputText("/offwarn ")
sampSetChatInputEnabled(true)
end
if isKeyDown(key.VK_CONTROL) and wasKeyPressed(key.VK_NUMPAD7) then
sampSetChatInputText("/unwarn ")
sampSetChatInputEnabled(true)
end
if wasKeyPressed(key.VK_NUMPAD9) then
sampSetChatInputText("/ban ")
sampSetChatInputEnabled(true)
end
if isKeyDown(key.VK_MENU) and wasKeyPressed(key.VK_NUMPAD9) then
sampSetChatInputText("/offban ")
sampSetChatInputEnabled(true)
end
if isKeyDown(key.VK_MENU) and wasKeyPressed(key.VK_6) then
sampSetChatInputText("/unban ")
sampSetChatInputEnabled(true)
end
if isKeyDown(key.VK_MENU) and wasKeyPressed(key.VK_7) then
sampSetChatInputText("/sban ")
sampSetChatInputEnabled(true)
end
end
end
end


Изменено 29 августа, 2018 пользователем SHANZIX

оформление длинного кода

What Are Lua Errors?

A Lua error is caused when the code that is being ran is improper. There are many reasons for why a Lua error might occur, but understanding what a Lua error is and how to read it is an important skill that any developer needs to have.

Effects of Errors on Your Scripts

An error will halt your script’s execution when it happens. That means that when an error is thrown, some elements of your script might break entirely. For example, if your gamemode has a syntax error which prevents init.lua from executing, your entire gamemode will break.

Lua Error Format

The first line of the Lua error contains 3 important pieces of information:

  • The path to the file that is causing the error
  • The line that is causing the error
  • The error itself

Here is an example of a code that will cause a Lua error:

local text = «Hello World»
Print( text )

The code will produce the following error:

[ERROR]addons/my_addon/lua/autorun/server/sv_my_addon_autorun.lua:2: attempt to call global ‘Print’ (a nil value)
1. unknown addons/my_addon/lua/autorun/server/sv_my_addon_autorun.lua:2

That is because Print is not an existing function (print, however, does exist).

The first line includes the path to the file that is causing the error — addons/my_addon/lua/autorun/server/sv_my_addon_autorun.lua

Afterwards, the line that’s producing the error — sv_my_addon_autorun.lua:2 (Line 2)

Lastly, the error itself — attempt to call global ‘Print’ (a nil value)

Below the error, we have the trace of the function. Simplified — If the error is inside a function/chunk of code that is called from somewhere else, it will state where the code is called from.

If the error happens serverside, the text color will be blue. If it happened clientside, it will be yellow. If it’s menu code, it will be green (not a typical scenario). Messages which look like errors but are colored differently, such as red or white, are not Lua errors but rather engine errors.

Printing Your Own

If you want to print your own error messages, there are three functions to do it:

  • error will print your message, halt execution, and print the stack. Normal error behavior.
  • ErrorNoHalt will print the file/line number and your message without halting the script. Useful for warning messages.
  • assert will check to make sure that something is true. If it’s not, it will print your message and halt just like error does.

Common Errors

Attempt to call global ‘?’ a nil value

Description: You tried to call a function that doesn’t exist.

Possible causes:

  • Your function might be defined in another Lua state. (e.g Calling a function on the client that only exists on the * server.)
  • You’re using a metafunction on the wrong kind of object. (e.g. Calling :SteamID() on a Vector)
  • The function you’re calling has an error in it which means it is not defined.
  • You’ve misspelled the name of the function.

Ways to fix:

  • Make sure the function exists
  • Make sure your function is defined in the correct realm
  • Check your function calls for spelling errors

Attempt to perform arithmetic on global ‘?’ (a nil value)

Description: You tried to perform arithmetic (+, -, *, /) on a global variable that is not defined.

Possible causes:

  • You tried to use a local variable that was defined later in the code
  • You’ve misspelled the name of the global variable

Ways to fix:

  • Make sure you define local variables before calling them in the code
  • Check for spelling errors

Attempt to perform arithmetic on ‘?’ (a type value)

Description: You tried to perform arithmetic (+, -, *, /) on a variable that cannot perform arithmetic. (e.g. 2 + «some string»)

Attempt to index global ‘varname’ (a nil value)

Description: You tried to index an undefined variable (e.g. print( variable.index ) where variable is undefined)

Possible causes:

  • The variable is defined in a different realm
  • The variable is local and defined later in the code
  • You’ve misspelled the name of the variable

Ways to fix:

  • Make sure the variable is only accessed in the realm it was defined in
  • If the variable is local, define it before accessing it

Malformed number near ‘number’

Description: There is a malformed number in the code (e.g. 1.2.3, 2f)

Possible causes:

  • An IP address was written as a number instead of a string
  • Incorrect writing of multiplication of a number and a variable
  • Trying to concatenate a number to a string without a space between the number and the operator.

Ways to fix:

  • Store IP addresses as a string
  • Multiply variables with numbers by using the ***** operator
  • Put a space between the concat (..) operator and the number.

Unexpected symbol near ‘symbol’

Description: You typed a symbol in the code that Lua didn’t know how to interpret.

Possible causes:

  • Incorrect syntax (e.g. Forgot to write «then» after an if statement)
  • Not closing brackets and parentheses at the correct locations

Ways to fix:

  • Make sure there are no mistypes in the code
  • Close brackets and parentheses correctly (See: Code Indentation)

‘symbol1’ expected near ‘symbol2’

Description: Lua expected symbol1 instead of symbol2.
When ‘symbol2’ is <eof>, Lua expected a symbol before the end of the file

Possible causes:

  • Not closing all brackets, parentheses or functions before the end of the file
  • Having too many end statements
  • Wrong operator calling (e.g. «==» instead of «=»)
  • Missing comma after table item.

Ways to Fix

  • Close brackets and parentheses correctly (See: Code Indentation)
  • Use the correct operators
  • Add a comma after a table item

Содержание

  1. Ошибка: lua:103: unexpected symbol near ‘,’
  2. Вопрос
  3. SHANZIX 0
  4. Поделиться сообщением
  5. 3 ответа на этот вопрос
  6. Рекомендуемые сообщения
  7. Присоединяйтесь к обсуждению
  8. О нас
  9. Lua error unexpected symbol near
  10. Lua error unexpected symbol near
  11. Ошибка: unexpected symbol near
  12. Вопрос
  13. HeroBrine1st 87
  14. Поделиться сообщением
  15. 2 ответа на этот вопрос
  16. Рекомендуемые сообщения
  17. Присоединяйтесь к обсуждению
  18. О нас
  19. UTF-8 BOM и QLua скрипты
  20. Внимание

Ошибка: lua:103: unexpected symbol near ‘,’

Вопрос

SHANZIX 0

  • Посетитель
  • Пользователи 0
  • 6 публикаций

Нашел админ-хелпер для сампа, решил переписать под другой сервер, выходит ошибка, не могу найти где именно. Помогите!

Где «******», это убрал название форума, дабы не было рекламы.

Изменено 29 августа, 2018 пользователем SHANZIX
оформление длинного кода

Поделиться сообщением

Ссылка на сообщение
Поделиться на других сайтах

3 ответа на этот вопрос

Рекомендуемые сообщения

Присоединяйтесь к обсуждению

Вы можете написать сейчас и зарегистрироваться позже. Если у вас есть аккаунт, авторизуйтесь, чтобы опубликовать от имени своего аккаунта.

О нас

Проект ComputerCraft.ru основан в 2014 году. Особенностью наших игровых серверов является обязательное наличие компьютерных и технических модов и аддонов. Когда мод ComputerCraft устарел и больше не отвечал техническим требованиям, ему на замену пришел современный и высокотехнологичный мод OpenComputers. Черепашек заменили роботы из мода Opencomputers.

ComputerCraft.ru — это площадка для игры в Minecraft и общения на форуме, стабильные серверы и возможность в легкой и игровой форме обучиться программированию на языке Lua и реализовать все свои самые смелые инженерные идеи и решения и поделиться ими с другими игроками. За все время существования проекта сменилось 10 игровых серверов, которые посетили более 9000 игроков. На сайте собрано множество интересных программ и библиотек, статей, гайдов, веселых историй и горячих обсуждений, выдвинуто множество идей автоматизации и способов программирования.

У нас играют и пишут программы как новички так и опытные программисты. А самые продвинутые участники нашего коллектива даже разрабатывают собственные авторские моды и аддоны, ресурспаки, репозитории, мощнейшие библиотеки и операционные системы.

Регистрируйтесь прямо сейчас и присоединяйтесь к нашему дружному коллективу фанатов игры Minecraft , компьютерных и инженерных модов!

Источник

Lua error unexpected symbol near

So I have an error when trying to launch my DarkRP server.

The full error says:

[ERROR] addons/darkrpmodification-master/lua/darkrp_customthings/jobs.lua:22: unexpected symbol near ‘=’

Here is my code of line 22 and around:

color = Color(20, 150, 20, 255),
model =
«models/player/Group01/Female_01.mdl»,
«models/player/Group01/Female_02.mdl»,
«models/player/Group01/Female_03.mdl»,
«models/player/Group01/Female_04.mdl»,
«models/player/Group01/Female_06.mdl»,
«models/player/group01/male_01.mdl»,
«models/player/Group01/Male_02.mdl»,
«models/player/Group01/male_03.mdl»,
«models/player/Group01/Male_04.mdl»,
«models/player/Group01/Male_05.mdl»,
«models/player/Group01/Male_06.mdl»,
«models/player/Group01/Male_07.mdl»,
«models/player/Group01/Male_08.mdl»,
«models/player/Group01/Male_09.mdl»
>,
description = [[You are boring and can’t do anything fun as this job. This isn’t The Sims! Be something else!]],
weapons = <>,
command = «citizen»,
max = 0,
salary = GAMEMODE.Config.normalsalary,
admin = 0,
vote = false,
hasLicense = false,
candemote = false,
category = «The Ordinary»,
>)

If you guys know that the error might be somewhere else, let me know and I will post the full code.

Need help ASAP as I needed this server up by this weekend at the very most.

Источник

Lua error unexpected symbol near

I’m trying to run some great scripts I copied from the ReaTeam Script Repository and most worked perfectly, but there are 4 of them that I cannot figure out what it is I’m doing wrong.

Some of the errors that pop up are:
1: unexpected symbol near ‘//’
8: syntax error near ‘>’
1: unexpected symbol near ‘/’
6: ‘)’ expected (to close ‘(‘ at line 5) near ‘?’
5: ‘)’ expected near ‘?’

I’ll be honest, they sound like silly errors and the «unexpected symbol near xxx» I solve by just erasing the developer’s comments in the .lua text file.

Anyone can help? I tried for hours and I really don’t get this stuff.

the last 3 are similar.

I’d really appreciate any pointers, thanks!!

Firstly the better way is to just use ReaPack, so you can mark only these 4 script to download (not the whole package). This was created to make all things below easier so you shouldnt care about them.

Otherwise you have to deal with next things:
1. Make sure you copy code properly.
1a. Code wasn`t saved with «Save link as».
1b. Code was copied exact from right beginning until the end.
1c. You didn`t copy html stuff or different github info with code.
2. You saved code with proper extension. If they are .eel links why did you think these are LUA scripts?

So again, if you not so much into scripting shit, I suggest you to use extension manager instead.

Источник

Ошибка: unexpected symbol near

Вопрос

HeroBrine1st 87

Сделал я значит себе блютуз в ОС (знаю, есть такой, но код я воровать не хочу). Отдебажил все, но тут ошибка

Я проверил все несколько раз, пытался добавить и убрать скобку, минификатор так же видит эту ошибку, но при этом никакая конфигурация скобок не помогает решить проблему. В общем, помогите мне решить эту проблему.

Поделиться сообщением

Ссылка на сообщение
Поделиться на других сайтах

2 ответа на этот вопрос

Рекомендуемые сообщения

Присоединяйтесь к обсуждению

Вы можете написать сейчас и зарегистрироваться позже. Если у вас есть аккаунт, авторизуйтесь, чтобы опубликовать от имени своего аккаунта.

О нас

Проект ComputerCraft.ru основан в 2014 году. Особенностью наших игровых серверов является обязательное наличие компьютерных и технических модов и аддонов. Когда мод ComputerCraft устарел и больше не отвечал техническим требованиям, ему на замену пришел современный и высокотехнологичный мод OpenComputers. Черепашек заменили роботы из мода Opencomputers.

ComputerCraft.ru — это площадка для игры в Minecraft и общения на форуме, стабильные серверы и возможность в легкой и игровой форме обучиться программированию на языке Lua и реализовать все свои самые смелые инженерные идеи и решения и поделиться ими с другими игроками. За все время существования проекта сменилось 10 игровых серверов, которые посетили более 9000 игроков. На сайте собрано множество интересных программ и библиотек, статей, гайдов, веселых историй и горячих обсуждений, выдвинуто множество идей автоматизации и способов программирования.

У нас играют и пишут программы как новички так и опытные программисты. А самые продвинутые участники нашего коллектива даже разрабатывают собственные авторские моды и аддоны, ресурспаки, репозитории, мощнейшие библиотеки и операционные системы.

Регистрируйтесь прямо сейчас и присоединяйтесь к нашему дружному коллективу фанатов игры Minecraft , компьютерных и инженерных модов!

Источник

UTF-8 BOM и QLua скрипты

Внимание

Цитата
Борис Мурашов написал:
Добрый день, при создании файлов .lua в большинстве IDE файлы в UTF-8 кодировке создаются с BOM, при попытке исполнения таких скриптов возникает ошибка: «Syntax error while compiling *путь до файла скрипта*:1: unexpected symbol near ‘п’». Удалять BOM руками для каждого нового скрипта уже после 3 раза немного надоедает. Если есть возможность исправить, то буду рад этому. Версия РМ 7.14.1.7. Спасибо.

lua машина кушает исходный текст в Анси. Использование других кодировок внесёт неопределенность в синтаксический анализатор.

поэтому вариантов 2. Или сменить ide на тот, где можно задать кодировку для типа исходного текста либо обучить idе предварительной транслитерации текста в Анси перед сохранением и дальнейшими действиями над текстом.

Цитата
» target=»_blank» rel=»nofollow»>s_mike@rambler.ru написал:
lua машина кушает исходный текст в Анси. Использование других кодировок внесёт неопределенность в синтаксический анализатор.

поэтому вариантов 2. Или сменить ide на тот, где можно задать кодировку для типа исходного текста либо обучить idе предварительной транслитерации текста в Анси перед сохранением и дальнейшими действиями над текстом.

Столкнулся с этим же при попытке использования ZeroBrane Studio, которая, насколько я понял, работает исключительно с UTF-8. А Quik наоборот, работает исключительно с Win CP1251, иначе выдаёт ошибку загрузки скрипта.

Как бы их скрестить по-человечески. кто-то пробовал?

Цитата
s_mike@rambler.ru написал:
lua машина кушает исходный текст в Анси. Использование других кодировок внесёт неопределенность в синтаксический анализатор.

поэтому вариантов 2. Или сменить ide на тот, где можно задать кодировку для типа исходного текста либо обучить idе предварительной транслитерации текста в Анси перед сохранением и дальнейшими действиями над текстом.

Столкнулся с этим же при попытке использования ZeroBrane Studio, которая, насколько я понял, работает исключительно с UTF-8. А Quik наоборот, работает исключительно с Win CP1251, иначе выдаёт ошибку загрузки скрипта.

Источник

function funCMD.vac(id)
    if thread:status() ~= "dead" then
        sampAddChatMessage("{FFFFFF}[{EE4848}MedicalHelper{FFFFFF}]: В данный момент проигрывается отыгровка.", 0xEE4848)
        return
    end
    ---1758.8267822266   -2020.3171386719   1500.7852783203
    ---1785.8004150391   -1995.7534179688   1500.7852783203
    if not u8:decode(buf_nick.v):find("[а-яА-Я]+%s[а-яА-Я]+") then
        sampAddChatMessage("{FFFFFF}[{EE4848}MedicalHelper{FFFFFF}]: Подождите-ка, сначала нужно заполнить базовую информацию. {90E04E}/mh > Настройки > Основная информация", 0xEE4848)
        return
    end
    if id:find("%d+") then
        thread = lua_thread.create(function()
            if not isCharInModel(PLAYER_PED, 416) then
                sampSendChat(string.format("Здраствуйте.Что бы успешно вакцинироваться нужно 2 укола. 1 укол стоит 75.000$ ", u8:decode(buf_nick.v)))
                wait(1000)
                    sampAddChatMessage("{FFFFFF}[{EE4848}MedicalHelper{FFFFFF}]: Нажмите на  {23E64A}Enter{FFFFFF} для продолжения.", 0xEE4848)
                    addOneOffSound(0, 0, 0, 1058)
                    local len = renderGetFontDrawTextLength(font, "{FFFFFF}[{67E56F}Enter{FFFFFF}] - Продолжить")
                    while true do
                        wait(0)
                        renderFontDrawText(font, "Вакцинация: Согласие", sx-len-10, sy-50, 0xFFFFFFFF)
                        if isKeyJustPressed(VK_RETURN) and not sampIsChatInputActive() and not sampIsDialogActive() then break end
                    end
                sampSendChat(chsex("/me достав из мед.сумки шприц с вакциной, положил его на стол", "/me достав из мед.сумки шприц с вакциной, положила его на стол"))
                wait(2000)
                sampSendChat(chsex("/me просунув руку в правый карман куртки достал из него пару перчаток, затем одел их", "/me просунув руку в правый карман куртки достала из него пару перчаток, затем одела их"))
                wait(2000)
                sampSendChat(chsex("/me достав из левого кармана анти-септик, тщательно обработал им руки", "/me достав из левого кармана анти-септик, тщательно обработала им руки"))
                wait(2000)
                sampSendChat("/do В шприцу находиться нужная доза вакцины.")
                wait(2000)
                sampSendChat(chsex("/me несколькими движениями рук нашел нужное лекарство в мед.чемодане", "/me несколькими движениями рук нашла нужное лекарство в мед.чемодане"))
                wait(2000)
                sampSendChat("/do Лекарство в правой руке.")
                wait(2000)
                sampSendChat(chsex("/me сняв защитный колпачок, выдавил воздух из шприца", "/me сняв защитный колпачок, выдавила воздух из шприца"))
                wait(2000)
                sampSendChat("/me аккуратным движением руки передал лекарство пациенту")
                wait(2000)
                sampSendChat("/me достав из мед.сумки ватки и спирт, обмакнул ватку в спирт затем обработал область укола")
                wait(2000)
                sampSendChat("/todo Сейчас не дёргайтесь, будет немного не приятно*смотря на область укола")
                wait(2000)
                sampSendChat("/me аккуратным движением руки ввёл шприц в руку, затем вакцину")
                wait(2000)
                sampSendChat("/todo Вот и всё, держите ватку*передавая ватку человеку")
                wait(2000)
                sampSendChat("/me выкинув шприц в урну")
                wait(2000)
                sampSendChat("/todo Держите её в месте укола 2 минуты*передавая ватку человеку на против")
                sampAddChatMessage("WARN - Стойте 2 минуты около пациента. Отыгровка продолжиться автоматически!")
                sampSendChat("/vaccine "..id)
                wait(125000)
                sampSendChat("/vaccine "..id)
                wait(2000)
                sampSendChat("Могу Вас поздравить с успешным вакцинированием.")
                wait(2000)
                sampSendChat("Если будут жалобы на самочувствие - сразу же обратитесь к нам.")           
              end)
        else
        sampAddChatMessage("{FFFFFF}[{EE4848}MedicalHelper{FFFFFF}]: Используйте команду /vac [id].", 0xEE4848)
        end
end

Old
02-04-2018, 11:21 PM

 
#2

Human being with feelings

 

mpl's Avatar

 

Join Date: Oct 2013

Location: Moscow, Russia

Posts: 3,722

Default


Firstly the better way is to just use ReaPack, so you can mark only these 4 script to download (not the whole package). This was created to make all things below easier so you shouldnt care about them.

Otherwise you have to deal with next things:
1. Make sure you copy code properly.
1a. Code wasn`t saved with «Save link as».
1b. Code was copied exact from right beginning until the end.
1c. You didn`t copy html stuff or different github info with code.
2. You saved code with proper extension. If they are .eel links why did you think these are LUA scripts?

So again, if you not so much into scripting shit, I suggest you to use extension manager instead.


Last edited by mpl; 02-04-2018 at 11:41 PM.

mpl is offline

 

Reply With Quote

Old
02-04-2018, 11:39 PM

 
#3

Human being with feelings

 

Join Date: Jun 2017

Posts: 39

Default
Solved!!


Quote:

Originally Posted by mpl
View Post

2. You saved code with proper extension. If they are .eel links why did you think these are LUA scripts?

Thanks, man! It works! Downloading ReaPack now. This was driving me completely nuts!! LOL

And thank you again for taking the time to answer…

BaniBani is offline

 

Reply With Quote

Old
02-05-2018, 03:56 AM

 
#4

Human being with feelings

 

Join Date: May 2016

Posts: 720

Default


Konechno.

Even if you’re a coder yourself you have to be quite careful when copying scripts by hand. But I’m betting the problem here is the EEL/Lua misnaming.

You can think of it roughly like this. REAPER is like a Platoon, and four of the men are language experts. What you’ve done here is send orders written in EEL but marked on the envelope as being in Lua. The Commander has looked at your envelope and passed the orders on to Pvt Larry Lua instead of Pvt Eric EEL. Pvt Lua doesn’t speak EEL, so he doesn’t understand the orders.

Jason Lyon is offline

 

Reply With Quote

Hello,
I am new to Lua and when I run the following code, I always get the same errormessage saying: «test.lua:1: unexpected symbol near » » «.. Am I forgeting something?.. Here is my samplecode:

#include <iostream.h>
extern «C»
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
#include <luabind/luabind.hpp>
using namespace luabind;

class CTest
{
public:
CTest(){};
void Boo(){ cout << «LLaP»; }
};

int main( int argc , char* argv [])
{
lua_State* luaVM = lua_open();
luabind::open( luaVM);

module( luaVM)
[
class_(«Test»)
.def(constructor<>())
.def(«Boo», &CTest::Boo)
];

lua_dofile( luaVM, «test.lua»);

lua_close( luaVM);
cin.get();
return 0;
}
*—— test.lua ——*
T = Test()
T:Boo()

Change:
#include <iostream.h>
to:
#include <iostream>
maybe?

I changed it in #include <iostream> but when I do that I»ll get compiler-errors :

error C2065: »cout» : undeclared identifier
error C2297: »<<» : illegal, right operand has type »char [5]»
error C2065: »cin» : undeclared identifier
error C2228: left of ».get» must have class/struct/union type
Error executing cl.exe.

Of course… using namespace std!
I changed it and it compiled but I still get the former error:
test.lua:1: unexpected symbol near » » … I don»t understand why…

quote:Original post by moboko
Of course… using namespace std!
I changed it and it compiled but I still get the former error:
test.lua:1: unexpected symbol near » » … I don»t understand why…

I can»t really take a peek at the code just yet to see what»s going on. I»m in the midst of a move right now across the country and my home gear is still in transit. I»ll take a peek at the problem here in the next couple of days (when my stuff lands), unless you get a fix before hand.

Humble,Yet l33t

Okay, thx for the effort Ashley Matheson… good luck with your «translation» through the country…. I»ll have cleaned and rebuild the Lua5.0 and the luabind-b6 libs. Tomorrow I»ll test them and see if I»ll get the same error…

Aaaah…. I solved the problem… I used notepad and/or wordpad to edit my scriptfiles, these editors set extra control-characters in the files invisible to the eye, but visible to
the lua-interpreter… using my plain old dos-edit solves the problem :-)….

quote:Original post by moboko
Aaaah…. I solved the problem… I used notepad and/or wordpad to edit my scriptfiles, these editors set extra control-characters in the files invisible to the eye, but visible to
the lua-interpreter… using my plain old dos-edit solves the problem :-)….

Really? I’ve never had that problem with lua. Even older version.

And it’s Ash.

[edited by — ashleymatheson on January 23, 2004 5:13:38 PM]

Humble,Yet l33t

So You didn»t have this problem I had with the control-chars Mr. Ashley?…. hmmm, that sounds strange indeed… I noticed by accident that the filesize was different between 2 lua-scripts that looked apparently the «same»… So I opened the file that had a bigger size and saw a couple of extra control-chars in it…. The only thing I noticed aside from this was when I used «setlocale( LC_ALL, NULL);» before the lua_dofile… the lua_dofile returned a different error-code…. maybe it has something to do with the language and region settings but I am not familiar with that, so it remains a guess to me… thanks for your reactions and have a nice time on your new location Mr. Ashley.

Понравилась статья? Поделить с друзьями:
  • Lua error stdin 1 attempt to call field alarm a nil value
  • Lua error stalker
  • Mail socket error 10061
  • Mail ru секретный вопрос как изменить
  • Mail ru ошибка отправки