Lua error что это

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. An error will h..

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

lua-error

Robust error handling for Lua which features:

  • try(), catch(), finally() functions
  • custom error objects

Quick

-- import creates a base Error class and global funcs try(), catch(), finally()

local Error = require 'lua_error'


-- do this anywhere in your code:

try{
  function()
    -- make a call which could raise an error
  end,
  
  catch{
    function( err )
      -- handle the error
    end
  },
  
  finally{
    function()
      -- do some cleanup
    end
  }
}

Note: the catch{} and finally{} are optional.

Overview

The library is a culmination of several ideas found on the Internet put into a cohesive package. It was also inspired by the error handling in Python. (see References below)

There are two different components to this library which can either be used together or independently:

  1. Gobal functions: try, catch, and finally which give structure
  2. Error object class: which can be used by itself or subclassed for more refined errors

Lua Errors

The basic pieces of error handling built into Lua are the functions error() and pcall(). We only need to focus on error(), since that’s what we use to raise an error condition in a program, like so:

error( "this is my error" )

that in turn will create something like this:

my_lua_file.lua:17: this is my error
stack traceback:
	[C]: in function 'error'
	/path_to_file/my_lua_file.lua:17: in main chunk
	[C]: in function 'require'
	?: in function 'require'
	/path_to_file/main.lua:104: in function 'main'
	/path_to_file/main.lua:110: in main chunk

In the error we can see our error string «this is my error» and the corresponding traceback.

As shown in our simple example, error() is often only used to create string-type errors. There are a couple of drawbacks to these types of errors in that they are:

  1. they are fragile

Is that string «ProtocolError» from my module or yours? If string «out of data» changes then my code will break

  1. they are harder to represent other, finer-grained errors

Like error.overflow, app.error.protocol, etc

Though one feature of error() which can help is that its argument can be anything, not just a string, so later we’ll give it some Error objects.

try(), catch(), finally()

This function trio is the backbone of awesome error handling. The following is the basic structure using all three of the functions.

Note: in the example below, <func ref> represents a function reference, for example:

local func_ref = function() end

try{
  <func ref>,
  
  catch{
    <func ref>
  },
  
  finally{
    <func ref>
  }
}

This format works because it takes advantage of Lua’s dual-way to call functions, eg:

hello() or hello{}, the latter being equivalent to hello( {} )

So essentially this format is really a function try() which accepts a single array argument containing up to three function references like so, { <func ref>, catch{}, finally{} }.

Keep in mind that the terms catch and finally are themselves global functions just like try, and like try these each take a single array argument but contain only a single function like so { <func ref> }.

Here are some alternate layouts showing the same thing:

flattened out:
try{ <func ref>, catch{ <func ref> }, finally{ <func ref> } }

same thing, including parens:
try({ <func ref>, catch({ <func ref> }), finally({ <func ref> }) })

Custom Errors

The objects in this framework use lua-objects as the backbone.

Here’s a quick example how to create a custom error type:

-- import module
local Error = require 'lua_error'

-- create custom error class
-- this class could be more complex,
-- but this is all we need for a custom error
local ProtocolError = newClass( Error, { name="Protocol Error" } )

-- raise an error
error( ProtocolError( "bad protocol" ) )

For more examples of custom errors, you can check out the unit tests or the projects dmc-wamp, lua-bytearray, etc.

Example

The following code snippet is a real-life example taken from dmc-wamp:

	try{
		function()
			self._session:onOpen( { transport=self } )
		end,

		catch{
			function(e)
				if type(e)=='string' then
					error( e )
				elseif e:isa( Error.ProtocolError ) then
					print( e.traceback )
					self:_bailout{
						code=WebSocket.CLOSE_STATUS_CODE_PROTOCOL_ERROR,
						reason="WAMP Protocol Error"
					}
				else
					print( e.traceback )
					self:_bailout{
						code=WebSocket.CLOSE_STATUS_CODE_INTERNAL_ERROR,
						reason="WAMP Internal Error ({})"
					}
				end
			end
		}
	}

In the catch you see that:

  • first, we’re checking to see if it’s a regular string-type error. if so, re-raise the error since we only care about Error objects.
  • second, by using the method isa, see if the error is type ProtocolError, bailout with protocol error.
  • third, it’s not an error we can handle, so bailout with an internal error.

###References###

  • https://gist.github.com/cwarden/1207556
  • http://www.lua.org/pil/8.4.html
  • http://www.lua.org/wshop06/Belmonte.pdf

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,


Need for Error Handling

Error handling is quite critical since real-world operations often require the use of complex operations, which includes file operations, database transactions and web service calls.

In any programming, there is always a requirement for error handling. Errors can be of two types which includes,

  • Syntax errors
  • Run time errors

Syntax Errors

Syntax errors occur due to improper use of various program components like operators and expressions. A simple example for syntax error is shown below.

a == 2

As you know, there is a difference between the use of a single «equal to» and double «equal to». Using one instead of the other can lead to an error. One «equal to» refers to assignment while a double «equal to» refers to comparison. Similarly, we have expressions and functions having their predefined ways of implementation.

Another example for syntax error is shown below −

for a= 1,10
   print(a)
end

When we run the above program, we will get the following output −

lua: test2.lua:2: 'do' expected near 'print'

Syntax errors are much easier to handle than run time errors since, the Lua interpreter locates the error more clearly than in case of runtime error. From the above error, we can know easily that adding a do statement before print statement is required as per the Lua structure.

Run Time Errors

In case of runtime errors, the program executes successfully, but it can result in runtime errors due to mistakes in input or mishandled functions. A simple example to show run time error is shown below.

function add(a,b)
   return a+b
end

add(10)

When we build the program, it will build successfully and run. Once it runs, shows a run time error.

lua: test2.lua:2: attempt to perform arithmetic on local 'b' (a nil value)
stack traceback:
	test2.lua:2: in function 'add'
	test2.lua:5: in main chunk
	[C]: ?

This is a runtime error, which had occurred due to not passing two variables. The b parameter is expected and here it is nil and produces an error.

Assert and Error Functions

In order to handle errors, we often use two functions − assert and error. A simple example is shown below.

local function add(a,b)
   assert(type(a) == "number", "a is not a number")
   assert(type(b) == "number", "b is not a number")
   return a+b
end

add(10)

When we run the above program, we will get the following error output.

lua: test2.lua:3: b is not a number
stack traceback:
	[C]: in function 'assert'
	test2.lua:3: in function 'add'
	test2.lua:6: in main chunk
	[C]: ?

The error (message [, level]) terminates the last protected function called and returns message as the error message. This function error never returns. Usually, error adds some information about the error position at the beginning of the message. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message.

pcall and xpcall

In Lua programming, in order to avoid throwing these errors and handling errors, we need to use the functions pcall or xpcall.

The pcall (f, arg1, …) function calls the requested function in protected mode. If some error occurs in function f, it does not throw an error. It just returns the status of error. A simple example using pcall is shown below.

function myfunction ()
   n = n/nil
end

if pcall(myfunction) then
   print("Success")
else
	print("Failure")
end

When we run the above program, we will get the following output.

Failure

The xpcall (f, err) function calls the requested function and also sets the error handler. Any error inside f is not propagated; instead, xpcall catches the error, calls the err function with the original error object, and returns a status code.

A simple example for xpcall is shown below.

function myfunction ()
   n = n/nil
end

function myerrorhandler( err )
   print( "ERROR:", err )
end

status = xpcall( myfunction, myerrorhandler )
print( status)

When we run the above program, we will get the following output.

ERROR:	test2.lua:2: attempt to perform arithmetic on global 'n' (a nil value)
false

As a programmer, it is most important to ensure that you take care of proper error handling in the programs you write. Using error handling can ensure that unexpected conditions beyond the boundary conditions are handled without disturbing the user of the program.

From Wikipedia, the free encyclopedia

This essay describes error and advisory messages (such as Script error) when running Lua scripts in Wikipedia.

Script error[edit]

Almost any problem which occurs when running a Lua module will be reported as «Script error» during program execution, such as invalid data or a misspelled variable name in the Lua source code. Although that message typically indicates a logic error inside the Lua script, it can also occur when a Lua function has been stopped due to a timeout limit (see below: Lua timeout error), and no actual bug is inside the Lua script. To determine the exact cause of script errors, it might be necessary to view-source to inspect the generated HTML code for the page.

The error reporting in Lua modules is extremely limited and poor, as if Lua had been designed by copying the work of computer scientists but developed by novices with almost no broad experience in using computer languages. Consequently, it is often necessary to write debugging functions into Lua modules, to show the status of the related variables just before a script error occurs. A common tactic is to show trace statements or «print statements» which can indicate the program flow as it leads up to a specific script error. By that method, the related script section, where a script error has occurred, can be pinpointed more precisely, along with showing the values of related variables at that time. For more, see: wp:Lua debugging.

Modern computer languages typically have a variety of specific error messages which help to pinpoint the error conditions, but not Lua, and those messages require space to store, and so, tiny computers often report short cryptic messages, even though a large number of errors could be pinpointed with specific messages itemizing the related details when an error was detected. Also, there has been a tendency to quietly ignore unknown/misspelled words in languages, in case those words would be added as new features in the future, which would require allowing the words to be accepted as non-error conditions. For those reasons, computers can be much harder to use now than they were years ago, when many computer systems were carefully designed by professionals to store details related to errors, while new features would be carefully designed, implemented and tested in an upgrade to a system, and so error messages could pinpoint what was incompatible with the overall, coherent design. However, the error detection and reporting, of specific error conditions, can often double or triple the complexity of software, and so that is another reason to just report «Script error» when fatal conditions occur, rather than carefully engineer a more-complex system to track and report the specific details.

For example, many misspelled keywords are unlikely to become «new features» and so common misspellings could be detected and reported to a user, but that would require extra effort to handle. The Lua language has allowed misspelled, or uninitialized, variables to be used in a script which can eventually cause «script error» while giving no other indication of the misspelled name or invalid data.

Lua timeout error[edit]

When a page has hit the Lua timeout limit (such as 10 seconds in February 2013), then the page will contain span-tags with class=»scribunto-error» such as:

  • <strong class=»error»><span class=»scribunto-error» id=»mw-scribunto-error-246″>Script error<!—The time allocated for running scripts has expired.—></span></strong>

Also, the bottom of the page might contain the message:

  • «The time allocated for running scripts has expired.»

Typically, when a page is re-run with fewer Lua-based templates, then the timeout error will stop.

See also[edit]

  • wp:Lua in Wikipedia
  • wp:Lua debugging

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