スクリプティング言語
表示
はじめに
[編集]スクリプティング言語は、プログラムやタスクの自動化、既存のコンポーネントの制御や連携に使用されるプログラミング言語です。コンパイル言語と比較して、より簡単に習得でき、迅速な開発が可能という特徴を持っています。本書では、特に重要な3つのスクリプティング言語であるJavaScript、Ruby、Luaについて詳しく解説します。
JavaScript
[編集]JavaScriptは、当初Webブラウザ上で動作するスクリプティング言語として開発されましたが、現在ではサーバーサイド開発やデスクトップアプリケーション開発にも使用される汎用的な言語となっています。
基本的な言語機能
[編集]// モダンなクラス定義 class BankAccount { constructor(initialBalance = 0) { this.balance = initialBalance; } deposit(amount) { this.balance += amount; return this.balance; } withdraw(amount) { if (amount > this.balance) { throw new Error('残高不足です'); } this.balance -= amount; return this.balance; } getStatement() { return <code>現在の残高: ${this.balance}円</code>; } } // 非同期処理 async function processTransaction(account, amount) { try { const result = await account.deposit(amount); console.log(<code>取引成功: 残高 ${result}円</code>); } catch (error) { console.error('取引エラー:', error); } } // イベント処理とクロージャ function createCounter() { let count = 0; return { increment() { return ++count; }, decrement() { return --count; }, getCount() { return count; } }; }
モダンなJavaScript機能
[編集]// 分割代入とスプレッド演算子 const config = { host: 'localhost', port: 3000, ssl: true }; const { host, ...rest } = config; // Promiseチェーン function fetchUserData(userId) { return fetch(<code>/api/users/${userId}</code>) .then(response => response.json()) .then(data => { const { name, email } = data; return { name, email }; }) .catch(error => { console.error('ユーザーデータの取得に失敗:', error); throw error; }); }
Ruby
[編集]Rubyは読みやすさと書きやすさを重視した言語設計が特徴で、「プログラミングを楽しむ」という思想のもと開発されました。Webアプリケーションフレームワークのリファレンス実装としても知られています。
オブジェクト指向プログラミング
[編集]# クラスとモジュール module Loggable def log(message) puts "[#{Time.now}] #{self.class}: #{message}" end end class Task include Loggable attr_reader :title, :created_at def initialize(title) @title = title @created_at = Time.now @completed = false log("タスクが作成されました") end def complete @completed = true log("タスクが完了しました") end def completed? @completed end end # メソッド呼び出しの例 task = Task.new("重要な会議") puts task.title task.complete puts task.completed?
メタプログラミング機能
[編集]# 動的メソッド定義 class String def method_missing(method_name, *args) if method_name.to_s =~ /^to_(.+)_case$/ self.split('_').map(&:capitalize).join($1) else super end end end puts "hello_world".to_space_case # "Hello Space World" # クラスの拡張 class Module def attr_logged(*names) names.each do |name| define_method(name) do puts "属性 #{name} が参照されました" instance_variable_get("@#{name}") end define_method("#{name}=") do |value| puts "属性 #{name} が更新されました" instance_variable_set("@#{name}", value) end end end end
Lua
[編集]Luaは軽量で高速な組み込み用スクリプティング言語として知られ、特にゲーム開発で広く使用されています。シンプルな言語仕様と優れたパフォーマンスが特徴です。
基本文法とテーブル
[編集]-- テーブルを使用したオブジェクト指向プログラミング local Player = {} Player.__index = Player function Player.new(name, health) local self = setmetatable({}, Player) self.name = name self.health = health self.inventory = {} return self end function Player:takeDamage(amount) self.health = self.health - amount print(string.format("%sの残りHP: %d", self.name, self.health)) end function Player:addItem(item) table.insert(self.inventory, item) print(string.format("%sが%sを手に入れた", self.name, item)) end -- 使用例 local player = Player.new("勇者", 100) player:takeDamage(20) player:addItem("魔法の剣")
コルーチンと状態管理
[編集]-- コルーチンを使用した状態管理 function enemy_ai() local state = "patrol" local position = 0 while true do if state == "patrol" then position = position + 1 if position > 10 then state = "return" end elseif state == "return" then position = position - 1 if position < 0 then state = "patrol" end end print(string.format("現在位置: %d, 状態: %s", position, state)) coroutine.yield(position) end end -- AIの実行 local ai = coroutine.create(enemy_ai) for i = 1, 25 do coroutine.resume(ai) end
まとめ
[編集]JavaScript、Ruby、Luaはそれぞれ異なる用途と特徴を持つスクリプティング言語です。JavaScriptはWeb開発とクライアントサイドプログラミングで、Rubyは生産性の高いサーバーサイド開発で、Luaは組み込みシステムやゲーム開発で、それぞれ重要な役割を果たしています。これらの言語は、プログラミングの異なるニーズに応えつつ、高い生産性と柔軟性を提供しています。
参考文献
[編集]- ECMAScript仕様書
- Ruby言語仕様
- Programming in Lua(Roberto Ierusalimschy著) ISBN 978-8590379829