- Roblox Lua Style Guide¶
- Guiding Principles¶
- File Structure¶
- Prototype-based classes¶
- Guarding against typos¶
- General Punctuation¶
- General Whitespace¶
- Newlines in Long Expressions¶
- Error Handling¶
- Lua Globals
- Using the Lua Debugger
- What is a Debugger?
- Inspecting Breakpoints
- Stepping Through Code
- Watching Variables
- Call Stack
- What is ROBLOX Lua scripting? [closed]
- 7 Answers 7
- Создание игр для Roblox
- Чему научатся дети
- План обучения и проекты
- Трехмерное моделирование, работа с трехмерными объектами
- Проработка окружающего мира, основы программирования на Lua
- Программирование на Lua
- Разработка игры “Tower of hell”, часть 1
- Разработка игры “Tower of hell”, часть 2
- Разработка игры-кликера, Часть 1
- Разработка игры-кликера, Часть 2
- Свой проект
- Работы учеников
- Александр Хархота
Roblox Lua Style Guide¶
This style guide aims to unify as much Lua code at Roblox as possible under the same style and conventions.
This guide is designed after Google’s C++ Style Guide. Although Lua is a significantly different language, the guide’s principles still hold.
Files should consist of these things (if present) in order:
Use relative paths when importing modules from the same package.
Use absolute paths when importing modules from a different package.
Metatables are an incredibly powerful Lua feature that can be used to overload operators, implement prototypical inheritance, and tinker with limited object lifecycle.
At Roblox, we limit use of metatables to a couple cases:
The most popular pattern for classes in Lua is sometimes referred to as the One True Pattern. It defines class members, instance members, and metamethods in the same table and highlights Lua’s strengths well.
First up, we create a regular, empty table:
Next, we assign the __index member on the class back to itself. This is a handy trick that lets us use the class’s table as the metatable for instances as well.
We can also define methods that operate on instances. These are just methods that expect their first argument to be an instance. By convention, we define them using a colon ( : ):
At this point, our class is ready to use!
We can construct instances and start tinkering with it:
Further additions you can make to your class as needed:
Add a method to check type given an instance, like:
Guarding against typos¶
Indexing into a table in Lua gives you nil if the key isn’t present, which can cause errors that are difficult to trace!
Our other major use case for metatables is to prevent certain forms of this problem. For types that act like enums, we can carefully apply an __index metamethod that throws:
Since __index is only called when a key is missing in the table, MyEnum.A and MyEnum.B will still give you back the expected values, but MyEnum.FROB will throw, hopefully helping engineers track down bugs more easily.
No vertical alignment!
Use a single empty line to express groups when useful. Do not start blocks with a blank line. Excess empty lines harm whole-file readability.
Use one statement per line. Put function bodies on new lines.
This is especially true for functions that return multiple values. Compare these two statements:
It’s much easier to spot the mistake (and much harder to make in the first place) if the function isn’t on one line.
This is also true for if blocks, even if their body is just a return statement.
Most of the time this pattern is used, it’s because we’re performing validation of an input or condition. It’s much easier to add logging, or expand the conditional, when the statement is broken across multiple lines. It will also diff better in code review.
Put a space before and after operators, except when clarifying precedence.
Put a space after each commas in tables and function calls.
When creating blocks, inline any opening syntax elements.
Avoid putting curly braces for tables on their own line. Doing so harms readability, since it forces the reader to move to another line in an awkward spot in the statement.
Newlines in Long Expressions¶
First, try and break up the expression so that no one part is long enough to need newlines. This isn’t always the right answer, as keeping an expression together is sometimes more readable than trying to parse how several small expressions relate, but it’s worth pausing to consider which case you’re in.
It is often worth breaking up tables and arrays with more than two or three keys, or with nested sub-tables, even if it doesn’t exceed the line length limit. Shorter, simpler tables can stay on one line though.
Prefer adding the extra trailing comma to the elements within a multiline table or array. This makes it easier to add new items or rearrange existing items.
Break dictionary-like tables with more than a couple keys onto multiple lines.
Break list-like tables onto multiple lines however it makes sense.
For long argument lists or longer, nested tables, prefer to expand all the subtables. This makes for the cleanest diffs as further changes are made.
In some situations where we only ever expect table literals, the following is acceptable, though there’s a chance automated tooling could change this later. In particular, this comes up a lot in Roact code ( doSomething being Roact.createElement ).
However, this case is less acceptable if there are any non-tables added to the mix. In this case, you should use the style above.
For long expressions try and add newlines between logical subunits. If you’re adding up lots of terms, place each term on its own line. If you have parenthesized subexpressions, put each subexpression on a newline.
For long conditions in if statements, put the condition in its own indented section and place the then on its own line to separate the condition from the body of the if block. Break up the condition as any other long expression.
Use do blocks if limiting the scope of a variable is useful.
Use double quotes when declaring string literals.
Add trailing commas in multi-line tables.
Always use parentheses when calling a function. Lua allows you to skip them in many cases, but the results are typically much harder to parse.
Declare named functions using function-prefix syntax. Non-member functions should always be local.
Use single line comments for inline notes:
Use block comments for documenting items:
Comments should focus on why code is written a certain way instead of what the code is doing.
No section comments.
Some examples of ways of breaking up files:
If you can’t break the file up, and still feel like you need section headings, consider these alternatives.
If you want to put a section header on a group of functions, put that information in a block comment attached to the first function in that section. You should still make sure the comment is about the function its attached to, but it can also include information about the section as a whole. Try and write the comment in a way that makes it clear what’s included in the section.
The same can be done for a group of variables in some cases. All the same caveats apply though, and you have to consider whether one block comment or a normal comment on each variable (or even using just whitespace to separate groups) would be more readable.
Unintended yielding can cause hard-to-track data races. Simple code involving callbacks can cause confusing bugs if the input callback yields.
Do not throw errors except when validating correct usage of a function.
The following is a list of functions and variables that are native to Lua. These functions can be used in a standard installation of Lua 5.1.4, though there are some differences in how some of these work on Roblox.
Throws an error if the provided value is false or nil. If the assertion passes, it returns all values passed to it.
Performs an operation on the Lua garbage collector based on the specified option.
Roblox’s Lua sandbox only allows the “count” option to be used, so none of the other standard options are available.
The “count” option returns the total memory in use by Lua (in kilobytes).
Terminates the last protected function called and outputs message as an error message. If the function containing the error is not called in a protected function (pcall), then the script which called the function will terminate. The error function itself never returns and acts like a script error.
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.
Returns the current environment in use by the caller.
Getting the Current Environment
Getting the Environment of a Function
Getting the Environment Based on Stack
Returns the metatable of the given table t if it has one, otherwise returns nil. If t does have a metatable, and the __metatable metamethod is set, it returns that value instead.
Returns three values: an iterator function, the table t and the number 0. Each time the iterator function is called, it returns the next numerical index-value pair in the table. When used in a generic for-loop, the return values can be used to iterate over each numerical index in the table:
Loads Lua code from a string, and returns it as a function.
Unlike standard Lua 5.1, Roblox’s Lua cannot load the binary version of Lua using loadstring.
The behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may, however, modify existing fields. In particular, you may clear existing fields.
Returns an iterator function, the passed table t and nil, so that the construction will iterate over all key/value pairs of that table when used in a generic for-loop:
Calls the function func with the given arguments in protected mode. This means that any error inside func is not propagated; instead, pcall catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall also returns all results from the call, after this first result. In case of any error, pcall returns false plus the error message.
Checks whether v1 is equal to v2, without invoking any metamethod.
Gets the real value of table[index], without invoking any metamethod.
Sets the real value of table[index] to a given value, without invoking any metamethod.
Returns all arguments after argument number index. If negative, it will return from the end of the argument list.
Returns the total number of arguments that were passed after the cmd argument, which must be «#» to use select in this fashion.
Sets the environment to be used by the given function. f can be a function or a number that specifies the function at that stack level: Level 1 is the function calling setfenv. setfenv returns the given function.
As a special case, when f is 0 setfenv changes the environment of the running thread. In this case, setfenv returns no values.
Attempts to convert the arg into a number with a specified base to interpret the value in. If it cannot be converted, this function returns nil.
The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter ‘A’ (in either upper or lower case) represents 10, ‘B’ represents 11, and so forth, with ‘Z’ representing 35. In base 10 (the default), the number may have a decimal part, as well as an optional exponent part. In other bases, only unsigned integers are accepted.
If a string begins with “0x” and a base is not provided, the 0x is trimmed and the base is assumed to be 16, or hexadecimal.
Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, use string.format. If the metatable of e has a __tostring metamethod, then it will be called with e as the only argument and will return the result.
Returns the type of its only argument, coded as a string. The possible results of this function are “nil” (a string, not the value nil), “number”, “string”, “boolean”, “table”, “function”, “thread”, and “userdata”.
Returns the elements from the given table. By default, i is 1 and j is the length of list, as defined by the length operator.
This function is similar to pcall, except that you can set a new error handler.
xpcall calls function f in protected mode, using err as the error handler, and passes a list of arguments. 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. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In this case, xpcall also returns all results from the call, after this first result. In case of any error, xpcall returns false plus the result from err.
A table that is shared between all scripts of the same context level.
A global variable (not a function) that holds a string containing the current interpreter version.
Using the Lua Debugger
The Lua debugger is a tool designed to give Roblox developers the same utilities as any developer expects from an IDE (Integrated Development Environment). It’s enabled by default, however it can be toggled on or off through Roblox Studio’s Settings menu.
What is a Debugger?
A debugger is a tool which helps developers check that their code is functioning properly. Some debugger functionality can be replicated with print() statements that verify when specific code executes, but a debugger lets you put breakpoints in your scripts without modifying the code. In addition, the application will stop at breakpoints, letting you inspect the state of the program and even the values of certain variables at that point.
Breakpoints are “checkpoints” within a script. If a breakpoint is set for a line of code, a running Roblox game will pause when it tries to execute that line.
To set a breakpoint within a script:
Stepping Through Code
When a script is paused at a breakpoint, you can continue executing the script line by line. This lets you closely monitor how variables are changed and which functions are called. There are three ways to step through code, all available from in the Script Menu tab:
|Step Into||The Step Into button moves the debugger into the function on the current line. If there is no function on the current line, the debugger will move to the next line.|
|Step Over||The Step Over button moves the debugger to the next line of code, not moving into functions.|
|Step Out||The Step Out button moves the debugger out of the current function and to the next line of code after the function was initially called. If the current line is not inside a function, this button will move to the next line.|
You can also tell the debugger to “watch” variables, keeping track of their value when you hit breakpoints. To add a variable to the watch list, simply highlight it and click the Add Watch button from the Script Menu tab. This will open the Watch window where you can monitor the variable’s value as you step through breakpoints.
The Call Stack window, accessible from the View tab, tells you exactly where in your code the game currently is (when paused or at a breakpoint). If the current line of code exists inside a function that was called from another function, the stack will show the order in which the functions were called, along with the line number where the call was made.
server-side `Script|Scripts`, not on client-side `LocalScript|LocalScripts`. This means that you can’t debug `LocalScript|LocalScripts` while testing your game in **Client** mode during a `articles/game testing|Play Solo` simulation. To debug client-side `LocalScript|LocalScripts` instead of server-side `Script|Scripts`, you can enable the Debug Client in APS Mode setting within Studio. This will allow you to insert breakpoints, step through code, and inspect the call stack of client-side code.
What is ROBLOX Lua scripting? [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
I really dont understand what it really even is. Is it just normal scripting or something else?
7 Answers 7
Lua is a fairly well known and often embedded scripting language.
However, if you’re after some basic «getting starting» information on Roblox scripting, check out the Roblox Wiki. (The tutorial’s section would probably be of specific interest.)
Lua is a well known scripting and programming language that is lightweight and easy to learn. Many games have embedded it, including Garry’s Mod (GMod) and World of Warcraft.
ROBLOX uses Lua to actually create games. Most of the features you see in ROBLOX (like the GUI and building tools) are actually coded in Lua.
I’d recommend seeing games by Anaminus, VolcanoINC and Telamon to see what you could do with Lua.
Lua is a scripting language somewhat similar to Java. Infact, I recall there being a Javalua blend as a scripting language in itself. Lua is probably the easiest scripting language to learn and work with. Its functions are fired by changes specified such as script.Parent.Value.Changed:connect(functionnamehere)
Parents are what the script or item specified is in. Variables work like this:
If a ROBLOX Solo Game is the source and v’s script.Parent’s name (script.Parent.Name) is ScriptFireValue then v is equal to d.
The language also includes loops that are recognizable like
‘for’ is a limited loop where it only loops for a certain amount of times. exe.
I think a few more.
Here’s an example script I’m writing off the top of my head. The source I’m going off of is ROBLOX’s Build/Edit mode in-game.
That script if not obvious identified the player who clicked. (clicker). Btw the argument ‘clicker’ would be identified the cause of the function to be fired. So the cause is because a button was ‘Clicked’. So ‘clicker’ retrieves the person who initiated that. Therefore identifying if the player is a certain person which would allow the process to continue. So if the player’s name is coolboy10000 then it will gather all the players and kill them each.
To put a security on that button to where if the player is not coolboy10000 then the player will be killed you could do this:
If there are multiple people to allow to do this function you could do:
Or if there is a specific person who should have a separate punishment:
Yeah that’s just the basics :/ There are tutorials out there. Mostly on ROBLOX free models. I say you should study some free scripts and learn how they work and stuff. This is just the basics. There is a tutorial on ROBLOX. Just search in Free Models scripting tutorials. Some dude wrote in scripts how to script. It’s pretty long to read but that’s how I learned.
Создание игр для Roblox
Ученики научатся создавать игровой мир и 3D‑модели для своих игр, а потом оживлять этот мир с помощью программирования на Lua.
Чему научатся дети
На практическом курсе по созданию игр на Roblox дети научатся
План обучения и проекты
Трехмерное моделирование, работа с трехмерными объектами
1. Интерфейс Роблокс-студио, изучение процесса создания игры.
2. Дизайн игрового пространства
3. Создание сложных объектов
4. Работа с объектами из тулбокса и знакомство со скриптом
Проработка окружающего мира, основы программирования на Lua
1. Блочное моделирование
2. Особенности создания пути игрока
3. Разработка игровой локации
4. Доработка игровой локации
Программирование на Lua
1. Работа с памятью компьютера, переменные в Lua
2. Циклы: бесконечный цикл, цикл с условием выхода в Lua
3. Создание космической станции, часть 1
4. Создание космической станции, часть 2
Разработка игры “Tower of hell”, часть 1
2. Функции и события в Lua, скрипт KillScript
3. Лестницы, как способ углубления геймплея
Разработка игры “Tower of hell”, часть 2
1. Углубленное изучение TweenService
2. Изменение параметров анимации TweenService
3. Объединение скриптов TweenService и KillScript
4. Завершение работы над игрой
Разработка игры-кликера, Часть 1
1. Создание игры-кликера
2. Введение в графический интерфейс
3. Создание блоков взаимодействия
4. Интро, как элемент GUI
Разработка игры-кликера, Часть 2
1. Мультиплеер в Roblox, управление игроками
2. Мультиплеер: дизайн и скриптинг игрового Лобби
3. Доработка игры, дебаг и тестирование
4. Введение в игровой маркетинг
1. Разработка игрового мира
2. Скриптинг основного геймплея
3. Скриптинг GUI, доработка деталей
4. Презентация игры
Мы уверены, что учитьcя на практике эффективнее. Поэтому у нас нет скучных лекций, и на занятиях дети создают реальные игры и программы.
Flappy Bird — мой первый игровой проект на PyGame! Нажимайте «пробел» и прыгайте!
Собрала 17 фактов о животных на сайте. Нажимайте Пуск и читайте 🙂
Игра где вы сможете побыть рыбаком на причале или на лодке. На причале есть 5 видов рыб
Привет! ты попал в Minecraft 2D
Сибирский государственный университет телекоммуникаций и информатики
Уроки Roblox Studio - Создание 3D-игр - Урок 2 Основы языка Lua. Начинаем делать игруСкачать
Как Написать Свой СКРИПТ в Roblox Studio! (УРОК 1)Скачать
ROBLOX Туториал по скриптам 1# (lua)Скачать
Программирование на языке Lua. Книга Roblox: играй, программируй и создавай свои мирыСкачать
Пишем свой первый скрипт в Roblox Studio! #1| Roblox Studio Скриптинг Remastered |Скачать
Уроки Roblox Studio - Создание 3D-игр - Урок 1 Создание картыСкачать
Как написать свой Hack Script на Roblox #1 (Что такое Lua , и наш первый script )Скачать
ROBLOX STUDIO | С чего я начинал програмировать на LuaСкачать