- Small basic ��� linux
- Answered by:
- Question
- Answers
- Small Basic — для тех, кто только начинает
- Первый запуск.
- Приятные моменты.
- Аппендикс.
- Небольшой пример, разлетающиеся шарики.
- А теперь разберем код.
- Small basic ��� linux
- Latest commit
- Git stats
- Files
- README.md
- Ссылки для скачивания
- MS Small Basic
- MS .Net Franework
- SB-Prime
- Библиотеки
- Проекты
- Дополнительные программы
- User guide
- Constants and Variables
- Statement OPTION MATCH PCRE [CASELESS]|SIMPLE
- Compile-Time
- Statement OPTION PREDEF parameter
- Meta-commands
- The operator LIKE
- Single-line Functions
- Units
- The pseudo-operators
- The USE keyword
- The DO keyword
- Using LOCAL variables
- Loops and variables
- Loops and expressions
Small basic ��� linux
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I just installed new Linux Mint 13 codename:Maya on my laptop, I want to use/run small basic properly
I downloaded Wine for running .exe files but i can’t make it work.
What do i have to do to be able to properly use SB on linux 13 mint?
Answers
Thing is, you can’t.
Small Basic is compiled for the Common Language Runtime and uses the .NET Framework; neither of these are available on Linux. It also won’t run under WINE because WINE, to my knowledge, does not emulate a CLR environment, only a general Windows environment where programs written in native languages can run.
Small Basic could be made to be available on Linux, but it would require the source code. SB would have to be compiled against the Mono Runtime, which is available on Linux, OSX, Windows, iOS, and Android. However, I doubt MS are going to let us have all the resources for Small Basic (source code, GUI elements, imagery, etc).
Short answer: you cannot make Small Basic run on Linux; you require Windows.
I have indeed tried to run SB through WiNE almost a year ago.
Although WiNE doesn’t emulate a .NET VM Framework, neither Windows itself. It needs to be installed, just like Java VirtualMachine for example! That’s what I did!
After installing .Net Framework 3.5 SP1 inside WiNE (w/ a lil’ help of winetricks script), I was at least able to run SB‘s TextWindow based compiled programs in Linux!
But nothing else -> neither GraphicsWindow based .exe nor SB‘s IDE itself. *_*
AFAIK, WiNE is still unable to emulate WPF and other related .Net 3+ graphics features.
My advise would be to run a Windows (XP, 7, 8. ) as a guest OS, using a machine emulator like VirtualBox or VMPlayer, etc.
You just need to install the whole OS (from a real optical media or an ISO image of it) inside a virtual disk provided by the emulator, just like you would in a real machine.
After that, you can install and run your favorite Windows-only programs there at the same time as the host OS.
P.S.: As a general rule, WiNE is über faster than a full machine emulator. Thus, it’s preferable to try to run a program under WiNE 1st, before relying on a machine emu!
Click on «Propose As Answer» if some post solves your problem or «Vote As Helpful» if some post has been useful to you! (^_^)
Источник
Small Basic — для тех, кто только начинает
Всем привет, а особенный привет тем, кто хочет начать программировать, и не знает на чем начать и какую среду разработки предпочесть.
Сегодня я расскажу о такой замечательной вещи как Small Basic.
И все же, для кого Small Basic? Логично — для тех кто хочет начать программировать. Для того что бы начать программировать опыт совершенно не нужен, но если есть — это даже лучше.
Весьма не плохо было-бы, если попутно, на уроках информатики старших классов школы или студентов, помимо паскаля и турбо-бейсика выделяли часы на Small Basic, было бы полезно.
Первый запуск.
Очень хорошее окошко, ничего лишнего.
Приятные моменты.
Вот за это отдельное спасибо, это очень удобная вещь. Управление стрелками, русское описание. Ваши назначенные переменные так-же поддерживаются. Процесс становиться очень приятным.
Аппендикс.
На сайте microsoft, и при установке так же ставиться начальная документация, которая очень понятным языком познакомит вас с Small Basic и самим процессом программирования в целом.
К сожалению у SB не очень большие возможности. Но это позволяет ученику, после достаточного усвоения SB перейти на более профессиональный уровень.
SB поддерживает подключение внешних библиотек, которые значительно расширяют возможности.
Для русских есть официальное русскоязычное сообщество начинающих программистов. Там-же доступна версия 0.8
Преимущества очевидны, если для всеми известного «первого приложения» Hello Word в Small Basic’е достаточно:
TextWindow.WriteLine(«hello word»)
C++
main()
<
cout
На языке pascal
program HelloWorld(output);
begin
WriteLn(‘Hello World!’);
end.
Выбирать конечно Вам, но разница ощутима, хотя я никак не сравниваю C++ программирование с Small Basic, но на чем изучать
Небольшой пример, разлетающиеся шарики.
Самое интересное то, что программа всего в 15 строчек:
For i = 1 To 100
balls[i] = Shapes.AddEllipse(10, 10)
EndFor
While «True»
For i = 1 To 100
ball = balls[i]
x = Math.GetRandomNumber(640)
y = Math.GetRandomNumber(480)
Shapes.Animate(ball, x, y, 2000)
EndFor
Program.Delay(1900)
EndWhile
А теперь разберем код.
Исходный код можно поделить на 2 части.
Первая операция For — цикл, с помощью этого цикла мы зададим нашей переменной начальное и конечное значение, прирост переменной будет делаться автоматически, компьютером.
В цикл мы добавим переменную, назовем ее «balls», и внутри переменной дадим команду SB «Shapes», она позволяет добавлять, двигать и вращать фигуры, к объекту (Shapes) добавим операцию «AddEllipse» которая служит для добавления эллипса с заданной высотой и шириной. Цикл заканчиваем командой EndFor.
Во второй части кода мы опять же используем цикл, но другой конструкции. Другая конструкция необходима в том случае, если переменная счетчика-цикла не известна заранее, если цикл For выполняется столько раз, сколько мы зададим, то цикл While выполняется до тех пор, пока не выполнит условие.
В цикл While мы включаем цикл For, в котором мы создадим переменную ball равную balls[i] (i — все значения от 1 до 100).
Добавим переменные для координат x и y. Для этого воспользуемся классом Math, который предоставляет множество математических операций. К классу припишем операцию GetRandomNumber, которая дает случайное число в заданном параметре maxNumber, который в свою очередь мы укажем в скобках.
Далее опять даем команду SB «Shapes», но на этот раз приписываем операцию Animate, которая перемещает фигуру (ball) с помощью анимации на новую позицию (x,y) и поставим время анимации в секундах 2000. Заканчиваем цикл For командой EndFor.
Используем класс Program, который служит для контроля самого приложения, приписываем к нему операцию Delay, которая задерживает выполнение программы на 1900 мс. И в конце останавливаем цикл While командой EndWhile.
Источник
Small basic ��� linux
SmallBASIC is a fast and easy to learn BASIC language interpreter ideal for everyday calculations, scripts and prototypes. SmallBASIC includes trigonometric, matrices and algebra functions, a built in IDE, a powerful string library, system, sound, and graphic commands along with structured programming syntax
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
SmallBASIC is a fast and easy to learn BASIC language interpreter ideal for everyday calculations, scripts and prototypes. SmallBASIC includes trigonometric, matrices and algebra functions, a built in IDE, a powerful string library, system, sound, and graphic commands along with structured programming syntax.
Building the SDL version
Initial setup on linux
Build the debian package
or for cross-compiling under linux:
Note: requires building SDL2 and freetype-2 into the prefix folder
Building on MacOSX
Open the terminal window, then type the following commands at the prompt:
Next download the SmallBASIC source code from git and then build:
Then type the following to run the executable:
Building the non-graphical console version (cygwin or linux)
Windows 32 bit mingw console:
Windows 64 bit mingw console:
Building the Android port
- Build FreeType First, prepare the cross-compiler from the NDK:
Then use it to cross-compile the tools:
Useful adb commands for debugging: adb shell dumpsys cpuinfo adb shell top -m 10
Источник
Ссылки для скачивания
MS Small Basic
Microsoft Small Basic 1.2 — Русский (с сайта Microsoft , с сайта Small Basic )
В пакет входит компилятор MS Small Basic, IDE от Microsoft, стандартная библиотека расширения, включающая библиотеку MS Kinect.
MS .Net Franework
Microsoft .Net Framework необходим для работы MS Small Basic. Рекомендуется версия 4.8 или новее.
SB-Prime
Small Basic Prime 1.1.7 — Русская версия
SB Prime — самая удобная и функциональная среда для программирования на языке MS Small Basic. В пакет входит русифицированная среда разработки SB-Prime. Для работы необходима установка MS Small Basic 1.2 и Microsoft .Net Framework не ниже версии 4.5.
Библиотеки
Библиотека LitDev версии 1.2 — Русская версия
Самая качественная и многофункциональная библиотека для MS Small Basic, позволяющая делать на MS Small Basic практически все что угодно.
Библиотека EV3 Basic — Русская версия
Библиотека для программирования роботов Lego EV3.
Проекты
Здесь представлены программные продуктоы, разработанные нами на MS Small Basic или переписанные специально для Small Basic. Некоторые из них создавались как учебные проекты, некоторые изначально проектировались для решения существующих задач. Все программы полностью работоспособны, безопасны и могут использоваться на правах свободно распространяемого ПО.
CF.exe — утилита создания пустого файла с заданным именем из командной строки. Версия 1. Версия 2. Описание и исходный код проекта.
PhotoDIR — утилита сортировки фотографий, видео и т.п. файлов, в имени которых присутствует дата, по папкам с именами дат.
SunSet — программа для проведения экспериментов: записи в файл и отображения на экране информации с датчика или измерительного прибора с заданным временным шагом в реальном времени в виде графиков и т.п.
Дополнительные программы
Текстовый редактор Notepad ++
Один из лучших многофункциональных текстовых редакторов, идеально подходящий для работы с текстами программ, имеет подсветку кода, автоматическую подсказку слов и огромный функционал, который может быть расширен с помощью плагинов.
Антивирус Avast
Очень полезная антивирусная программа, обеспечивающая действительно хорошую защиту от вирусов и атак по сети.
Лечащие программы Dr.Web CureIt! и Kaspersky Virus Removal Tool
Если вы предполагаете наличие вирусов на вашем компьютере, стоит провести проверку ваших файлов одной из этих программ (или обеими сразу). Программы не требуют установки на компьютер. Единственная задача, которую они отлично выполняют — поиск и уничтожение вирусов.
Блокировщик рекламы AdGuard
Надёжный блокировщик рекламы и отслеживания ваших действий в сети Интернет.
Сервис VirusTotal
Сервис VirusTotal позволяет проверить одиночные файлы или сайты (ссылки) по многим антивирусным базам в том случае, когда почему-либо отсутствует возможность воспользоваться антивирусом или необходимо проверить работу вашего антивируса, когда проверенный им файл всё равно вызывает какие-то подозрения.
Почему здесь присутствует ссылка на антивирусы и блокировщик рекламы и отслеживания? Потому что, во-первых, компьютерная безопасность в настоящее время — далеко не пустой звук, особенно при работе в интернет, а во-вторых, для того, чтобы вы гарантированно могли убедиться в безопасности всех скачиваемых на нашем сайте файлов.
Антивирус Avast в настоящее время является одним из самых надежных бесплатных антивирусов, а блокировщик рекламы AdGuard занимает первое место по эффективности и надёжности в мире. Даже если вы не собираетесь заниматься программированием, мы рекомендуем вам установить Avast и AdGuard.
Источник
User guide
SmallBASIC is a fast and easy to learn BASIC language interpreter ideal for everyday calculations, scripts and prototypes. SmallBASIC includes trigonometric, matrices and algebra functions, a built in IDE, a powerful string library, system, sound, and graphic commands along with structured programming syntax.
Constants and Variables
- All user variables (include arrays) are ‘Variant’. That means the data-type is invisible to user.
- Arrays are always dynamic, even if you had declared their size, with dynamic size and type of elements.
However, SmallBASIC uses, internally, 4 data-types
- Integer (32bit)
- Real (64bit)
- String ( sgn(b)))
+, — Addition/Concatenation, Subtraction = Equal <> or != Not Equal >, , = =, OPTION BASE statement sets the lowest allowable subscript of arrays to lower-bound. The default is zero. The OPTION BASE statement can be used in any place in the source code but that is the wrong use of this except if we have a good reason. In most cases the OPTION BASE must declared at first lines of the program before any DIM declaration. Statement OPTION MATCH PCRE [CASELESS]|SIMPLE
Sets as default matching algorithm to (P)erl-(C)ompatible (R)egular (E)xpressions library or back to simple one. Matching-algorithm is used in LIKE and FILES .
PRCE works only in systems with this library and it must be linked with. Also, there is no extra code on compiler which means that SB compiles the pattern every time it is used.
Compile-Time
Statement OPTION PREDEF parameter
Sets parameters of the compiler. Where parameter
- QUIET Sets the quiet flag (-q option)
- COMMAND cmdstr Sets the COMMAND$ string to var (useful for debug reasons)
- GRMODE [widthxheight[xbpp]] Sets the graphics mode flag (-g option) or sets the preferred screen resolution. Example: (Clie HiRes)
- TEXTMODE Sets the text mode flag (-g- option)
- CSTR Sets as default string style the C-style special character encoding (‘\’)
Meta-commands
Used by Unix to make source runs as a script executable
Used internally to store the section name. Sections names are used at limited OSes like PalmOS for multiple 32kB source code sections.
Used to include a SmallBASIC source file into the current BASIC code
Used to setup additional directories for searching for unit-files This meta does nothing more than to setting up the environment variable SB_UNIT_PATH. Directories on Unix must separated by ‘:’, and on DOS/Windows by ‘;’
That creates the array
11 12 21 22 31 32 The comma used to separate column items; the semi-colon used to separate rows. Values between columns can be omitted.
This creates the array
0 0 0 1 2 0 3 4 5 Supported operators: Add/sub:
There is a problem with 1 dimension arrays, because 1-dim arrays does not specify how SmallBASIC must see them.
1 2 3 And because this is not the same thing. (ex. for multiplication) So the default is columns DIM A(3) ’ or A(1,3)
For vertical arrays you must declare it as 2-dim arrays Nx1
1 2 3 Nested arrays are allowed
This will be printed
You can access them by using a second (or third, etc) pair of parenthesis.
The operator IN
IN operator is used to compare if the left-value belongs to right-value.
The operator LIKE
LIKE is a regular-expression operator. It is compares the left part of the expression with the pattern (right part). Since the original regular expression code is too big (for handhelds), I use only a subset of it, based on an excellent old stuff by J. Kercheval (match.c, public-domain, 1991). But there is an option to use PCRE (Perl-Compatible Regular Expression library) on systems that is supported (Linux); (see OPTION).
The same code is used for filenames (FILES(), DIRWALK) too. In the pattern string:
* matches any sequence of characters (zero or more) ? matches any character [SET] matches any character in the specified set, [!SET] or [^SET] matches any character not in the specified set. A set is composed of characters or ranges; a range looks like character hyphen character (as in 0-9 or A-Z). [0-9a-zA-Z_] is the minimal set of characters allowed in the [..] pattern construct. To suppress the special syntactic significance of any of []*?!^-\\’, and match the character exactly, precede it with a \’.
The pseudo-operator BYREF keyword for passing parameters ‘by reference’. Passing parameters by reference means the executor push the pointer of variable into the stack. The value in caller’s code will be the changed.
You can use the symbol @ instead of BYREF . There is no difference between @ and BYREF .
On a multi-section (PalmOS) applications sub/funcs needs declaration on the main section.
Use the LOCAL keyword for local variables. LOCAL creates variables (dynamic) at routine’s code.
You can send arrays as parameters. When using arrays as parameters its better to use them as BYREF ; otherwise their data will be duplicated in memory space.
Single-line Functions
There is also an alternative FUNC DEF syntax (single-line functions). This is actually a macro for compatibility with the BASIC’s DEF FN command, but quite useful.
Nested procedures and functions
One nice feature, are the nested procedures/functions. The nested procedures/functions are visible only inside the “parent” procedure/function. There is no way to access a global procedure with the same name of a local.
Units
Units are a set of procedures, functions and/or variables that can be used by another SB program or SB unit. The main section of the unit (commands out of procedure or function bodies) is the initialization code.
A unit declared by the use of UNIT keyword.
The functions, procedure or variables which we want to be visible to another programs must be declared with the EXPORT keyword.
Keep file-name and unit-name the same. That helps the SB to automatically recompile the required units when it is needed. To link a program with a unit we use the IMPORT keyword.
To access a member of a unit we must use the unit-name, a point and the name of the member.
The pseudo-operators
++/–/p= The ++ and – operators are used to increase or decrease the value of a variable by 1.
The generic p= operators are used as in C Where p any character of -+/\*^%&|
All these pseudo-operators are not allowed inside of expressions
The USE keyword
This keyword is used on specific commands to passing a user-defined expression.
In that example, every element of V() will be ‘trimmed’. Use the x variable to specify the parameter of the expression. If the expression needs more parameter, you can use also the names y and z
The DO keyword
This keyword is used to declare single-line commands. It can be used with WHILE and FOR-family commands.
Also, it can be used by IF command (instead of THEN), but is not suggested.
Using LOCAL variables
When a variable is not declared it is by default a global variable. A usual problem is that name may be used again in a function or procedure.
In this example, the result is a real mess, because the var i of the main loop will always (except the first time) have the value 6! This problem can be solved if we use the LOCAL keyword to declare the var in the function body.
It is good to declare all local variables on the top of the function. For compatibility reasons, the func./proc. variables are not declared as ‘local’ by default. That it is WRONG but as I said … compatibility.
Loops and variables
When we write loops it is much better to initialize the counters on the top of the loop instead of the top of the program or nowhere.
p.. Initializing variables at the top of the loop can make code more readable.
Loops and expressions
In that example the ‘destination’ is the LEN(FILES(«*.txt»))-1 For each value of i the destination will be evaluated. That is WRONG but it is supported by BASIC and many other languages. So, it is much better to be rewritten as
Источник